【发布时间】:2013-05-16 04:22:03
【问题描述】:
我有以下简单的控制器来捕获任何意外异常:
@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 测试框架编写集成测试。这是我目前所拥有的:
@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 抛出异常的期望。
异常被抛出,但 ExceptionController 没有处理它。
我希望能够测试 ExceptionController 是否获得异常并返回适当的响应。
对为什么这不起作用以及我应该如何进行这种测试有什么想法吗?
谢谢。
【问题讨论】:
-
我猜在测试异常处理程序时没有被分配,不知道确切原因,但这就是它发生的原因,看看这个答案stackoverflow.com/questions/11649036/…
-
有这方面的消息吗?我也有同样的情况。
-
我没有找到解决方案。我决定我会相信 @ExceptionHandler 的工作原理,并且由于方法本身很简单,我决定我可以不测试该注释而生活。您仍然可以使用常规单元测试来测试该方法。
-
可能您的异常扩展了 Throwable 而不是 Exception。我遇到了同样的问题并检查了 InvocableHandlerMethod 中的代码,该代码检查了
else if (targetException instanceof Exception) { throw (Exception) targetException; } -
检查this 解决方案是否有帮助。将 $.error 替换为 $.message
标签: spring spring-mvc mockito spring-mvc-test