C0d*_*ack 48 spring spring-mvc mockito spring-mvc-test
我有以下简单的控制器来捕获任何意外的异常:
@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获取异常并返回适当的响应.
有关为什么这不起作用以及我应该如何进行此类测试的任何想法?
谢谢.
Bri*_*ews 63
我刚才遇到了同样的问题,以下内容适用于我:
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(statusController)
.setControllerAdvice(new ExceptionController())
.build();
}
Run Code Online (Sandbox Code Playgroud)
此代码将添加使用异常控制建议的能力。
@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;
}
Run Code Online (Sandbox Code Playgroud)
由于您使用的是独立设置测试,因此您需要手动提供异常处理程序。
mockMvc= MockMvcBuilders.standaloneSetup(adminCategoryController).setSingleView(view)
.setHandlerExceptionResolvers(getSimpleMappingExceptionResolver()).build();
Run Code Online (Sandbox Code Playgroud)
几天前我遇到了同样的问题,你可以在这里看到我自己回答的问题和解决方案Spring MVC 控制器异常测试
希望我的回答对你有帮助
| 归档时间: |
|
| 查看次数: |
41144 次 |
| 最近记录: |