spring - 使用@WebFluxTest 测试 RouterFunction

标签 spring spring-boot testing spock spring-webflux

我有一个路由器功能,我想使用 spock 进行测试。看起来像这样

@Configuration
public class WebConfig {

    /**
     * Router function.
     * @return string
     */
    @Bean
    public RouterFunction<?> helloRoute() {
        return route(GET("/judge/router/hello"),
                request -> ServerResponse.ok().body(fromPublisher(Mono.just("Hello Router WebFlux"), String.class)));
    }

}

它的测试看起来像这样

@WebFluxTest
class JudgeRuleEngineMvcTestSpec extends Specification {

    @Autowired
    WebTestClient webClient;

    def "router function returns hello"() {
        expect:
            webClient.get().uri("/judge/router/hello")
                .exchange()
                .expectStatus().isOk()
                .expectBody(String.class)
                .isEqualTo("Hello WebFlux") // should fail
    }
}

但它失败了,因为它返回的不是 200 状态,而是 404。它似乎找不到 REST 本身。

我还使用 GetMapping 对基本 RestController 进行了测试,它工作正常。

@RestController
@RequestMapping("/judge/rest")
public class BasicController {
    private static final Logger LOGGER = LoggerFactory.getLogger(BasicController.class);

    @GetMapping("/hello")
    public Mono<String> handle() {
        LOGGER.debug("Invoking hello controller");
        return Mono.just("Hello WebFlux");
    }

}

def "mvc mono returns hello"() {
    expect:
        webClient.get().uri("/judge/rest/hello")
            .exchange()
            .expectStatus().isOk()
            .expectBody(String.class)
                .isEqualTo("Hello WebFlux")
}

为什么路由器功能失败了?

最佳答案

这是 @WebFluxTest 的一个已知限制 - 目前没有一致的方法来检测 RouterFunction bean,就像我们为 @Controller 类(class)。

参见 this Spring Boot issue for future reference .

关于spring - 使用@WebFluxTest 测试 RouterFunction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48842652/

相关文章:

Java WatchService 意外停止工作

spring - 带有 persistence.xml 的 Intellij JPA 控制台

spring - 如何在独立 Tomcat 中运行的 Spring Boot 应用程序中设置 cookie 名称?

java - java.lang.IllegalStateException:在堆栈上找不到调用#0。记录方法调用无效?

java - 如何在不覆盖 Spring Boot 使用的 bean 的情况下定义自定义 ObjectMapper bean

android - 在实际设备中安装 .apk 文件仅用于测试

testing - 提高移动应用程序测试人员测试技能的方法

java - Spring MVC 为匹配模式的所有 url 提供相同的静态内容

java - JPA,Spring映射多个实体

performance - token ID 及其脚本