【问题标题】:spring-mvc: how to test Rx responses with mockMvc?spring-mvc:如何使用 mockMvc 测试 Rx 响应?
【发布时间】:2016-10-21 13:06:59
【问题描述】:

我的控制器是:

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...

so:如何使用 spring mvc 测试rx.Single

【问题讨论】:

  • 请查看here提供的答案

标签: java spring spring-mvc testing rx-java


【解决方案1】:

我找到了答案。当您创建 mockMvc 对象时,为 Single 添加一个处理程序:

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

【讨论】:

    【解决方案2】:

    如果您改用MockMvcBuilders.webAppContextSetup(context),则可以在WebMvcConfigurerAdapter 中添加处理程序:

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

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 2014-01-25
      • 2014-05-31
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 2020-04-19
      • 2019-11-01
      • 2016-11-05
      相关资源
      最近更新 更多