javawebtestclient

Java WebTestClient without SpringBoot


Is it possible to use WebTestClient for API Testing without being in a Spring OR Spring Boot project? I know RestAssured allows API Testing regardless of project. Recieving error below

Error: java.lang.IllegalStateException: To use WebTestClient, please add spring-webflux to the test classpath.

The only maven import I want is spring-test:

Maven

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.31</version>
</dependency>

Java:

@Test
public void testData() {
    WebTestClient testClient = WebTestClient
            .bindToServer()
            .baseUrl("https://www.test.com")
            .build();

    String testBody = "testText";

    testClient.post()
            .uri("/data", "123")
            .body(Mono.just(testBody), String.class)
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk();

Solution

  • As the documentation states

    WebTestClient is an HTTP client designed for testing server applications. It wraps Spring’s WebClient and uses it to perform requests but exposes a testing facade for verifying responses.

    (emphasis mine). As such, it has a compile time dependency on WebClient. As stated by the error message you mentioned, WebClient is provided by the spring-webflux artifact, but as this documentation states, you'll also need an HTTP client library to provide the client implementation.

    You apparently want to bind to standalone running web server. Unfortunately, you'll need all the dependencies above to use WebTestClient in this way.

    without being in a Spring OR Spring Boot project

    I'm not sure what you mean by Spring Boot project, but the dependencies above are provided as simple JARs (for example), you just need to have them on your test run's classpath.