gpt4 book ai didi

java - Springs MockMvc 以两种略有不同的方法之一返回空内容

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:11:14 25 4
gpt4 key购买 nike

我正在测试一个 Spring MVC @RestController,它会依次调用外部 REST 服务。我使用 MockMvc 来模拟 spring 环境,但我希望我的 Controller 对外部服务进行真正的调用。手动测试 RestController 工作正常(使用 Postman 等)。

我发现如果我以特定方式设置测试,我会得到一个完全空的响应(状态代码除外):

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = AnywhereController.class)
public class AnywhereControllerTest{

@Autowired
private AnywhereController ac;

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

@Test
public void testGetLocations() throws Exception {

...

MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/anywhere/locations").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(containsString("locations")))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
.andReturn();
}

测试失败,因为内容和标题是空的。然后我尝试将其添加到测试类中:

@Configuration
@EnableWebMvc
public static class TestConfiguration{
@Bean
public AnywhereController anywhereController(){
return new AnywhereController();
}
}

此外,我还更改了 ContextConfiguration 注释(尽管我想知道这实际上做了什么):

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class AnywhereControllerTest{...}

现在突然所有检查都成功了,当打印内容正文时我得到了所有内容。

这里发生了什么?这两种方法有什么区别?

最佳答案

有人在评论中提到了@EnableWebMvc,结果证明这是正确的引导。我没有使用 @EnableWebMvc,因此

If you don't use this annotation you might not initially notice any difference but things like content-type and accept header, generally content negotiation won't work. Source

我对框架内部工作的了解有限,但启动期间的一个简单警告可能会节省很多调试时间。很有可能当人们使用@Configuration 和/或@RestController 时他们也想使用@EnableWebMvc(或它的xml 版本)。

更糟糕的是,例如 Spring Boot 会自动添加此注解,这就是为什么互联网上的许多教程(包括官方教程)都没有提到 @EnableWebMvc。

关于java - Springs MockMvc 以两种略有不同的方法之一返回空内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44856024/

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