[英]MockMvc is null when testing the Web Layer
我的应用程序中有这个 MvcTest:
@SpringBootTest
@WebMvcTest
public class BarsControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
但是当我运行测试时,mockMvc 在运行测试时为空。
您不应该同时使用@WebMvcTest
和@SpringBootTest
。
如果要同时测试 web 层和其他层,请一起使用@AutoConfigureMockMvc
和@SpringBootTest
:
@SpringBootTest
@AutoConfigureMockMvc
public class BarsControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
或者,如果您只想测试 web 层,您可以只使用@WebMvcTest
:注意这不会加载完整的 spring 应用程序上下文(它只加载 web 层)
@WebMvcTest
public class BarsControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.