使用 Spring MVC Test 测试 Spring MVC @ExceptionHandler 方法 [英] Testing Spring MVC @ExceptionHandler method with Spring MVC Test

查看:48
本文介绍了使用 Spring MVC Test 测试 Spring MVC @ExceptionHandler 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的控制器来捕捉任何意外的异常:

I have the following simple controller to catch any unexpected exceptions:

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity handleException(Throwable ex) {
        return ResponseEntityFactory.internalServerErrorResponse("Unexpected error has occurred.", ex);
    }
}

我正在尝试使用 Spring MVC 测试框架编写集成测试.这是我目前所拥有的:

I'm trying to write an integration test using Spring MVC Test framework. This is what I have so far:

@RunWith(MockitoJUnitRunner.class)
public class ExceptionControllerTest {
    private MockMvc mockMvc;

    @Mock
    private StatusController statusController;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(new ExceptionController(), statusController).build();
    }

    @Test
    public void checkUnexpectedExceptionsAreCaughtAndStatusCode500IsReturnedInResponse() throws Exception {

        when(statusController.checkHealth()).thenThrow(new RuntimeException("Unexpected Exception"));

        mockMvc.perform(get("/api/status"))
                .andDo(print())
                .andExpect(status().isInternalServerError())
                .andExpect(jsonPath("$.error").value("Unexpected Exception"));
    }
}

我在 Spring MVC 基础架构中注册了 ExceptionController 和一个模拟 StatusController.在测试方法中,我设置了从 StatusController 抛出异常的期望.

I register the ExceptionController and a mock StatusController in the Spring MVC infrastructure. In the test method I setup an expectation to throw an exception from the StatusController.

异常被抛出,但 ExceptionController 没有处理它.

The exception is being thrown, but the ExceptionController isn't dealing with it.

我希望能够测试 ExceptionController 是否获得异常并返回适当的响应.

I want to be able to test that the ExceptionController gets exceptions and returns an appropriate response.

对为什么这不起作用以及我应该如何进行这种测试有什么想法吗?

Any thoughts on why this doesn't work and how I should do this kind of test?

谢谢.

推荐答案

我刚刚遇到了同样的问题,以下对我有用:

I just had the same issue and the following works for me:

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(statusController)
         .setControllerAdvice(new ExceptionController())
        .build();
}

这篇关于使用 Spring MVC Test 测试 Spring MVC @ExceptionHandler 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆