使用自定义返回值处理程序进行MockMVC异步测试

时间:2015-04-17 15:29:41

标签: java spring spring-mvc spring-mvc-test

我正在尝试使用MockMvc以异步结果测试我的Spring 4.1控制器。我遵循了这里描述的相同模式:

https://github.com/spring-projects/spring-mvc-showcase/blob/master/src/test/java/org/springframework/samples/mvc/async/DeferredResultControllerTests.java

但是,我的测试是不同的,因为我正在使用这里描述的返回值处理程序:

https://github.com/AndreasKl/spring-boot-mvc-completablefuture

以下是我的测试代码:

public class MyControllerTest {

        private MockMvc mockMvc;
        private MyService myService;
        private MyController myController;

        public MappingJackson2HttpMessageConverter createMessageConverter() {

            ObjectMapper objectMapper = new ObjectMapper();
            List<MediaType> supportedMediaTypes = Arrays.asList(MediaTypes.JSON_V1);

            MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
            converter.setObjectMapper(objectMapper);
            converter.setSupportedMediaTypes(supportedMediaTypes);

            return converter;
        }

        @Before
        public void setup() throws Exception {   

            MappingJackson2HttpMessageConverter converter = createMessageConverter();
            myService = mock(MyService.class);

            controller = new MyController(myService);

            mockMvc = MockMvcBuilders.standaloneSetup(controller)
                .setMessageConverters(converter)
                .setCustomReturnValueHandlers(new CompletableFutureReturnValueHandler())
                .build();
        }

        @Test
        public void test() throws Exception {

            String value = "foo";
            CompletableFuture<ExampleData> futureValue = 
                CompletableFuture.completedFuture(new ExampleData(value));

            when(myService.getExample()).thenReturn(futureValue);

            MvcResult mvcResult = mockMvc.perform(get("/example"))
                .andExpect(status().isOk())
                .andExpect(request().asyncStarted())
                .andExpect(request().asyncResult(instanceOf(ExampleData.class)))
                .andReturn();

            mockMvc.perform(asyncDispatch(mvcResult))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaTypes.JSON_V1_VALUE))
                .andExpect(jsonPath("$.property", is(value)));
        }
}

似乎即使我使用StandaloneMockMvcBuilder.setCustomReturnValueHandlers()设置返回值处理程序,也永远不会调用它。这导致request()。asyncStarted()的断言失败,因为结果不是Callable或DeferredResult。

我是否正确设置了处理程序还是缺少其他东西?

====解决方案======

阅读完文档并逐步调试后,我发现setCustomReturnValueHandlers()将处理程序添加到列表的末尾,而spring-boot-mvc-completablefuture示例在DeferredResult处理程序之前插入它。使用非独立模式可以实现这一点。

0 个答案:

没有答案