java - spring-mvc:如何使用 mockMvc 测试 Rx 响应?

标签 java spring spring-mvc testing rx-java

我的 Controller 是:

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

最佳答案

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

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

关于java - spring-mvc:如何使用 mockMvc 测试 Rx 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40177473/

相关文章:

java - spring框架内置html/css/javascript输出编码?

Spring Boot CORS 过滤器 - CORS 预检 channel 未成功

java - 从具有 OutputStream 的 Spring @Controller 返回文件

java - setText 不适用

java - 从静态最终变量初始值设定项获取 Logger 是否有效?

javascript - 无法从使用 spring RedisTemplate 存储的 javascript 中获取 redis 嵌套哈希键值

java - 从页面实例中检索总元素 - Spring MVC

java - 在 RestTemplate 客户端获取从服务器抛出的异常的描述性自定义消息

java - 为什么在某些情况下重新抛出 Throwable 而不声明它是合法的?

java - Android Studio itemsAdapter 和自定义 ListView 不起作用