【发布时间】:2020-04-21 13:49:28
【问题描述】:
我的应用程序中目前有两个 ControllerAdvice,我应该将它们合并为一个。 但是我需要在合并之前和之后测试它们,测试异常和控制器返回给我的对象。
我正在尝试使用 Mockito 进行 jUnit 测试,但似乎无法在没有任何上下文、没有控制器等的情况下测试异常......
有谁知道我该如何继续实现我想要做的事情?
我也尝试手动抛出异常,但显然它没有被 ControllerAdvice 捕获。
所以基本上这就是我想要做的: 手动抛出异常 此异常由我的 ControllerAdvice 处理 检查返回的对象(代码和消息)
这是我的代码示例:
@Before
public void setup() {
...
mockMvc = MockMvcBuilders.standaloneSetup(getController())
.setControllerAdvice(new GlobalControllerExceptionHandler())
.setCustomArgumentResolvers(resolver, resolver_0, resolver_1)
.setHandlerExceptionResolvers(exceptionResolver).build();
}
@Controller
@RequestMapping("/tests")
public static class RestProcessingExceptionThrowingController {
@RequestMapping(value = "/exception", method = GET)
public @ResponseBody String find() {
throw new EntityNotFoundException();
}
}
@Test
public void testHandleException() throws Exception {
mockMvc.perform(get("/tests/exception"))
.andExpect(new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
result.getResponse().getContentAsString().contains("global_error_test");
}
})
.andExpect(status().isNotFound());
}
最后我有很好的状态码,但它不使用我的ControllerAdvice(我尝试使用调试器)
【问题讨论】:
标签: spring mockito mockmvc controller-advice