我正在尝试对控制器类进行单元测试,但遇到了以下错误。我尝试更改符号和遵循一些在线教程,但它一直不起作用,我总是得到这个相同的错误。下面是stackTrace:
java.lang.IllegalArgumentException: WebApplicationContext is required
at org.springframework.util.Assert.notNull(Assert.java:201)
at org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder.<init>(DefaultMockMvcBuilder.java:52)
at org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup(MockMvcBuilders.java:51)
at br.com.gwcloud.smartplace.catalog.controller.test.ItemControllerTest.setUp(ItemControllerTest.java:66)
...这是我的控制器测试类:
@SpringBootTest
@WebMvcTest(controllers = ItemController.class)
@ActiveProfiles("test")
@WebAppConfiguration
public class ItemControllerTest {
@MockBean
private ItemRepository ir;
@Autowired
private MockMvc mockMvc;
@Autowired
private ModelMapper modelMapper;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private ObjectMapper objectMapper;
@Before
public void setUp() {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.webApplicationContext);
this.mockMvc = builder.build();
}
@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());
}
}发布于 2021-10-11 13:07:33
您遇到的错误可以通过添加以下命令来解决:
@RunWith(SpringRunner.class)就在@SpringBootTest下面。或者,您也可以扩展AbstractJUnit4SpringContextTests。
另一个问题是@Before注释方法中的WebApplicationContext可能不可用。尝试将其移动到测试方法本身中。
也就是说,我通常会避免对控制器进行单元测试,因为我不会在其中放入任何业务逻辑。控制器所要做的就是指定路径、映射请求参数、错误处理(尽管在单独的ControllerAdvice类中处理会更好)、设置视图模型和视图目标等等。这些都是我所说的“管道”,并且与您正在使用的框架紧密相关。我不会对此进行单元测试。
相反,这种管道可以通过两个高级集成测试来验证,这些测试实际对控制器进行远程调用并执行完整的流程,包括所有管道。
任何业务逻辑都应该在控制器(通常是在服务中)之外进行,并在那里进行隔离的单元测试。
发布于 2021-10-11 13:07:57
您是否尝试过删除@SpringBootTest和@WebAppConfiguration。如果您只对测试控制器感兴趣,则不需要通过这些注释创建一个成熟的应用程序。
https://stackoverflow.com/questions/69526615
复制相似问题