gpt4 book ai didi

java - 不能 Mockbean HttpServletResponse

转载 作者:行者123 更新时间:2023-12-02 01:36:11 29 4
gpt4 key购买 nike

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

@RestController
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;

@Test
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

如何解决?

最佳答案

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

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

public class IndexTest {

private Index index = new Index();

@Test
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;

@Test
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;

@Test
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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com