sách gpt4 ai đã đi

Không thể Mockbean HttpServletResponse - Stack Overflow

In lại 作者:行者123 更新时间:2023-12-02 01:36:11 33 4
mua khóa gpt4 Nike

我可以在 Controller 中使用@Autowired,例如

@Bộ điều khiển nghỉ ngơi
public class Index {

@Autowired
HttpServletResponse response;

@GetMapping("/")
void index() throws IOException {
response.sendRedirect("http://example.com");
}
}

它有效;

但是当我尝试使用 @MockBean 测试此类时

@RunWith(SpringRunner.class)
@SpringBootTest
public class IndexTest {

@Autowired
Index index;

@MockBean
HttpServletResponse response;

@Bài kiểm tra
public void testIndex() throws IOException {
index.index();
}
}

它抛出异常并说

Description:

Field response in com.example.demo.Index required a single bean, but 2 were found:
- com.sun.proxy.$Proxy69@425d5d46: a programmatically registered singleton - javax.servlet.http.HttpServletResponse#0: defined in null


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

如何解决?

1 Câu trả lời

虽然可能恕我直言,但像这样注入(inject) HttpServletResponse hoặc HttpServletRequest 是一个坏习惯。这会导致奇怪的问题,而且看起来很奇怪又是错误的。而是使用 HttpServletResponse 类型的方法参数并使用 Spring MockHttpServletResponse用于测试。

然后编写单元测试就像创建类的新实例并调用该方法一样简单。

public class IndexTest {

private Index index = new Index();

@Bài kiểm tra
public void testIndex() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
index.index(response);
// Some assertions on the response.
}
}

如果您想将其作为更大的集成测试的一部分进行测试,您或多或少可以执行相同的操作,但使用 @WebMvcTest 注释。

@RunWith(SpringRunner.class)
@WebMvcTest(Index.class)
public class IndexTest {

@Autowired
private Index index;

@Bài kiểm tra
public void testIndex() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
index.index(response);
// Some assertions on the response.
}
}

或者使用MockMvc使用模拟请求进行测试

@RunWith(SpringRunner.class)
@WebMvcTest(Index.class)
public class IndexTest {

@Autowired
private MockMvc mockMvc;

@Bài kiểm tra
public void testIndex() throws IOException {
mockMvc.perform(get("/")).
andExpect(status().isMovedTemporarily());
MockHttpServletResponse response = new MockHttpServletResponse();
index.index(response);
// Some assertions on the response.
}
}

上面的测试也可以使用@SpringBootTest编写,区别在于@WebMvcTest只会测试和引导Web切片(即Web相关的东西),而 @SpringBootTest 实际上会启动整个应用程序。

关于java - 不能 Mockbean HttpServletResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55234478/

33 4 0
Bài viết được đề xuất: neo4j - 如何在 AuraDB 实例中编辑 neo4j.conf?
Bài viết được đề xuất: cython - 我的 Cython 有什么问题?
Bài viết được đề xuất: Groovy 元编程
Bài viết được đề xuất: c# - 当结果实现 IDisposable 时丢弃异步结果
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com