我有以下简单的控制器来捕获任何意外的异常:
@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是否获得异常并返回适当的响应。
有没有想过为什么这不能工作,以及我应该如何做这种测试?
谢谢。
发布于 2015-10-24 04:55:17
我刚刚遇到了同样的问题,下面的方法对我来说是有效的:
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(statusController)
.setControllerAdvice(new ExceptionController())
.build();
}发布于 2014-11-29 04:11:48
此代码将添加使用异常控制建议的功能。
@Before
public void setup() {
this.mockMvc = standaloneSetup(commandsController)
.setHandlerExceptionResolvers(withExceptionControllerAdvice())
.setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
}
private ExceptionHandlerExceptionResolver withExceptionControllerAdvice() {
final ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {
@Override
protected ServletInvocableHandlerMethod getExceptionHandlerMethod(final HandlerMethod handlerMethod,
final Exception exception) {
Method method = new ExceptionHandlerMethodResolver(ExceptionController.class).resolveMethod(exception);
if (method != null) {
return new ServletInvocableHandlerMethod(new ExceptionController(), method);
}
return super.getExceptionHandlerMethod(handlerMethod, exception);
}
};
exceptionResolver.afterPropertiesSet();
return exceptionResolver;
}发布于 2013-08-22 08:58:51
由于您使用的是独立安装测试,因此需要手动提供异常处理程序。
mockMvc= MockMvcBuilders.standaloneSetup(adminCategoryController).setSingleView(view)
.setHandlerExceptionResolvers(getSimpleMappingExceptionResolver()).build();前几天我也遇到了同样的问题,你可以在这里看到我的问题和解决方案,Spring MVC Controller Exception Test
希望我的回答能帮到你
https://stackoverflow.com/questions/16669356
复制相似问题