我的问题与测试使用@ExceptionHandler的Spring @RestController有关,这也使用了@ControllerAdvice。以下是代码:
@ControllerAdvice类:
@ControllerAdvice
public class MyAppExceptionHandler {
@ExceptionHandler({ NoSuchEntityException.class })
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public @ResponseBody
ErrorDTO handleNotFoundException(Exception ex) throws IOException {
return new ErrorDTO.Builder().setStatus(HttpStatus.NOT_FOUND)
.setCause(ex.getClass().getName())
.setThrowable(ex).build();
}
}
在应用程序中使用时一切正常,可以完美地获得404响应和JSON解释,但是在测试过程中尝试使用它时会出现问题。
我的测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { WebConfig.class })
@WebAppConfiguration
public class SomeTest {
@Mock
private SomeService service;
@InjectMocks
private SomeController controller;
private MockMvc mvc;
private ExceptionHandlerExceptionResolver createExceptionResolver() {
ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {
@Override
protected ServletInvocableHandlerMethod getExceptionHandlerMethod(
HandlerMethod handlerMethod, Exception exception) {
Method method = new ExceptionHandlerMethodResolver(
MyAppExceptionHandler.class).resolveMethod(exception);
return new ServletInvocableHandlerMethod(
new MyAppExceptionHandler(), method);
}
};
exceptionResolver.afterPropertiesSet();
return exceptionResolver;
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(controller)
.setHandlerExceptionResolvers(createExceptionResolver())
.build();
}
@Test
public void thatExceptionHappens() throws Exception {
when(service.get(10)).thenThrow(new NoSuchEntityException(Some.class, 10));
mvc.perform(get("/api/some/10")).andExpect(status().isNotFound());
}
}
尝试运行时:
2014-07-15 19:35:01.376 [main] ERROR com.package.SomeTest$1 - Failed to invoke @ExceptionHandler method: public com.package.ErrorDTO com.package.MyAppExceptionHandler.handleNotFoundException(java.lang.Exception) throws java.io.IOException
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
我认为可能在测试我的 @ExceptionHandler 时 MappingJackson2HttpMessageConverter 没有被加载(尽管它在WebConfig.class中进行了配置并且在尝试执行典型测试 - 不抛出任何异常的测试时,一切都正常运行)。
感谢您的帮助。