Spring Boot使用MockMVC测试控制器报WebApplicationContext is required错误如何解决
问题解决方法
报错的核心原因是测试类注解冲突,导致WebApplicationContext没有被正常实例化注入:@SpringBootTest是启动完整Spring上下文的集成测试注解,@WebMvcTest是专门用于控制器层切片测试的轻量级注解,二者同时使用会打乱上下文加载逻辑,最终触发空参数异常。
修复步骤
- 移除测试类上冗余的
@SpringBootTest和@WebAppConfiguration注解,@WebMvcTest本身已经内置了Web层测试需要的上下文配置能力,不需要额外补充这两个注解 - 删除
setUp方法中手动构建MockMvc的代码,@WebMvcTest会自动完成MockMvc的实例化并注入,重复手动构建反而会触发空指针问题 - 若项目中
ModelMapper没有被Spring自动扫描注册为Bean,可以在测试类上补充@Import(ModelMapper.class)注解完成依赖导入
修正后的测试类代码
@WebMvcTest(controllers = ItemController.class) @ActiveProfiles("test") // 若ModelMapper未自动注册,放开下面的Import注解 // @Import(ModelMapper.class) public class ItemControllerTest { @MockBean private ItemRepository ir; @Autowired private MockMvc mockMvc; @Autowired private ModelMapper modelMapper; @Autowired private ObjectMapper objectMapper; @Test public void shouldCreateNewItem() throws Exception { ItemDTO itemDTO = new ItemDTO(); itemDTO.setName("Leo"); itemDTO.setDescription("abc description"); itemDTO.setEnabled(true); itemDTO.setPartNumber("leo123"); Item item = itemDTO.convertToEntity(modelMapper); mockMvc.perform( post("/api/item/").contentType( MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(item))).andExpect( status().isOk()); } }
修复后@WebMvcTest只会加载控制器层相关的Bean,搭配@MockBean模拟依赖的Repository层实现,既满足控制器单元测试的需求,也不需要启动完整Spring上下文,测试执行效率更高。
内容的提问来源于stack exchange,提问作者leorosignoli
相关产品推荐
相关产品推荐

