2016-10-21 60 views
1

我的控制器:spring-mvc:如何使用mockMvc測試Rx響應?

import rx.Single; 
... 

@GetMapping 
Single<List<MyType>> fetchFromDB() { 
     return Single 
       .fromCallable(() -> dao.fetch()) 
       .subscribeOn(Schedulers.io()); 
} 

和它完美的作品。但我無法測試它。我想:

MvcResult asyncResult = mvc.perform(get("/")).andReturn() 

String result = mvc 
        .perform(asyncDispatch(asyncResult)) 
        .andReturn().getResponse().getContentAsString() 

,但它失敗:

java.lang.IllegalStateException: Async result for handler [rx.Single<java.util.List<MyType>> MyController.fetchFromDB()] was not set during the specified timeToWait=-1 

    at org.springframework.test.web.servlet.DefaultMvcResult.getAsyncResult(DefaultMvcResult.java:145) 
    at org.springframework.test.web.servlet.DefaultMvcResult.getAsyncResult(DefaultMvcResult.java:121) 
    at org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch(MockMvcRequestBuilders.java:246) 
    at MyControllerSpec.should fetch from db... 

如此:如何與Spring MVC的測試rx.Single

+0

請檢查答案提供[這裏](HTTPS ://stackoverflow.com/a/45033122/1290868) – myuce

回答

1

我找到了答案。當您創建mockMvc對象,添加一個處理Single

return MockMvcBuilders.standaloneSetup(controller) 
       .setCustomReturnValueHandlers(new SingleReturnValueHandler()) 
0

如果使用MockMvcBuilders.webAppContextSetup(context)相反,你可以添加處理程序在你的WebMvcConfigurerAdapter

public class Config extends WebMvcConfigurerAdapter { 

    @Override 
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { 
     returnValueHandlers.add(new SingleReturnValueHandler()); 
    } 
}