Search code examples
springspring-boottestingspockspring-webflux

Using @WebFluxTest to test RouterFunction


I've got a router function that I want to test using spock. It looks like this

@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)));
    }

}

The test for it looks like this

@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
    }
}

But it fails because instead of 200 status it returns 404. It seems it cannot find the REST itself.

I also has a test for basic RestController with GetMapping and it works fine.

@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")
}

Why it fails with router function?


Solution

  • It is a known limitation of @WebFluxTest - there is currently no consistent way to detect RouterFunction beans, just like we do for @Controller classes.

    See this Spring Boot issue for future reference.