使用Spring MVC测试来测试Spring MVC @ExceptionHandler方法 [英] Testing Spring MVC @ExceptionHandler method with Spring MVC Test
问题描述
我有以下简单的控制器可以捕获任何意外的异常:
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 Test框架编写集成测试.这是我到目前为止的内容:
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测试来测试Spring MVC @ExceptionHandler方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!