微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 使用@ControllerAdvice测试@RestController

我的问题与测试Spring @RestController有关,它也使用@ControllerAdvice和@ExceptionHandler.这是代码

@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();
    }
}

在应用程序中使用它时一切正常 – 通过JSON解释完美地获得404响应,但在测试期间尝试使用它时 – 会发生不好的事情.

我的考试班:

@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中配置,并且在尝试执行典型测试时 – 一个没有抛出任何异常 – 一切正常).

在此先感谢您的帮助.

最佳答案
我不确定这是否是最佳解决方案(我想听听另一个),
但这就是我如何解决你面临的问题:

将此行添加到createExceptionResolver():

exceptionResolver.getMessageConverters().add(
        new MappingJackson2HttpMessageConverter());

像这样的东西:

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.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    exceptionResolver.afterPropertiesSet();
    return exceptionResolver;
}

由于某些我不知道的原因,Spring没有加载我的MappingJackson2HttpMessageConverter.
这条线修复了我的问题.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐