英文:
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("$.length()", is(1)));
	}
}
但是当我运行测试时,mockMvc在运行测试时为null。
英文:
I have this MvcTest in my application:
@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)));
	}
}
but when I run the test mockMvc is null when running the tests.
答案1
得分: 1
不应该同时使用 @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)));
    }
}
英文:
You shouldn't use @WebMvcTest and @SpringBootTest together.
If you want to test both web layer and other layers Use @AutoConfigureMockMvc and @SpringBootTest  together:
@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)));
    }
}
Or if you only want to test web layer you can use just @WebMvcTest: note the this does not load full spring application context(It only loads web layer)
@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)));
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论