I want to test the following servlet:

@RestController
public class MyServlet {
    @PostMapping("/test")
    public Mono<String> test(HttpServletRequest req) {
        return Mono.just(req.getQueryString());
    }
}

The test fails:

@WebFluxTest(MyServlet.class)
public class MyServletTest {
    @Autowired
    private WebTestClient webClient;

    @Test
    public void testQuery() {
        webClient.post().uri("/test?query=param")
                .exchange()
                .expectStatus().isOk()
                .expectBody(String.class).isEqualTo("query=param");
    }
}

Result:

[][] 2020-03-12 12:05:19,727 ERROR o.s.b.a.w.r.e.AbstractErrorWebExceptionHandler: [7a3ea661]  500 Server Error for HTTP POST "/test?query=param"
java.lang.IllegalStateException: No primary or default constructor found for interface javax.servlet.http.HttpServletRequest
    at org.springframework.web.reactive.result.method.annotation.ModelAttributeMethodArgumentResolver.createAttribute(ModelAttributeMethodArgumentResolver.java:210) ~[spring-webflux-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 

spring-boot-2.2.5.RELEASE

Comment From: wilkinsona

You are using @WebFluxTest which enables Spring WebFlux. You cannot use HttpServletRequest with Spring WebFlux as it is Servlet-specific. You should be able to fix things by using spring-boot-starter-web and @WebMvcTest or @SpringBootTest .

If you have any further questions, please follow up on Stack Overflow or Gitter. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.

Comment From: membersound

But with @WebMvcTest I cannot test the return type of Mono<String>, that's why I'm using @WebFluxTest here?

Comment From: wilkinsona

If you return Mono<String> from a Spring MVC controller you are making use of Spring MVC async response support. You can find details of how to test such responses with MockMvc in Spring Framework's documentation.

As I said above, if you have any further questions, please follow up on Stack Overflow or Gitter. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.

Comment From: membersound

Ok, so mockMvc.perform(asyncDispatch(mvcResult)) is the answer here.

But probably the root cause is that I'm using HttpServletRequest, and instead I should be injecting ServerHttpRequest instead? As with this the WebTestClient works as expected with @WebFluxTest.

Comment From: cybuch

@membersound Yes, you should use org.springframework.http.server.reactive.ServerHttpRequest