我有以下简单的控制器来捕获任何意外的异常:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用Spring MVC Test框架编写集成测试.这是我到目前为止:
@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"));
}
}
Run Code Online (Sandbox Code Playgroud)
我在Spring MVC基础结构中注册了ExceptionController和一个模拟StatusController.在测试方法中,我设置了从StatusController抛出异常的期望.
抛出异常,但ExceptionController没有处理它.
我希望能够测试ExceptionController获取异常并返回适当的响应.
有关为什么这不起作用以及我应该如何进行此类测试的任何想法?
谢谢.
我想声明引发异常并且服务器返回500内部服务器错误.
要突出显示意图,请提供代码段:
thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
.contentType(MediaType.APPLICATION_JSON)
.content(requestString))
.andExpect(status().isInternalServerError());
Run Code Online (Sandbox Code Playgroud)
当然,无论我写作isInternalServerError还是写作都没关系isOk.无论是否在throw.except语句下方抛出异常,测试都将通过.
你会怎么解决这个问题?