如何在@ControllerAdvice 中测试异常处理

How to test exceptions handling in @ControllerAdvice

我目前在我的应用程序中有两个 ControllerAdvice,我应该将它们合并为一个。 但是我需要在合并前后测试它们,测试控制器return我的异常和对象。

我正在尝试使用 Mockito 进行 jUnit 测试,但似乎无法在没有任何上下文、没有控制器等的情况下测试异常...

有谁知道我该如何继续实现我想要做的事情?

我也尝试手动抛出异常,但显然它没有被 ControllerAdvice 捕获。

所以基本上这就是我正在尝试做的事情: 手动抛出异常 此异常由我的 ControllerAdvice 处理 检查 returned 对象(代码和消息)

这是我的代码示例:

@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(我尝试使用调试器)

直接调用handler方法即可

@ControllerAdvice

MyAdvice{

    @ExceptionHandeler(listOfExxcetpions)
    public ResponseEntity someOfMyExceptionsHandler(Exception e){
       .....
     }  

}

并在测试中

MuTest{
private MyAdvice advice=new MyAdvice();

@Test
public void oneOfTests(){
    Exception e=new SomeSortOfExceptionToTest();
    resp=advice.someOfMyExceptionsHandler(e)
    assertThat(resp).....dostuff;
}

}

如果你想测试 spring 如何与你的处理程序集成 - 如果你的注释正确,序列化顺序等 - 那么这将是一个集成测试,你必须启动测试上下文 - 那么你可以直接从控制器方法抛出异常。