Java WebTestClient without SpringBoot

139 Views Asked by At

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();
2

There are 2 best solutions below

0
Savior On BEST ANSWER

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.

4
F_sants_ On

WebTestClient is a wrapper of WebClient, so you need WebFlux on your classpath.

If you just need a web client, why don't you just use HttpClient from the JDK?

String testBody = "testText";

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
   .uri(new URI("https://www.test.com/data?123"))
   .POST(HttpRequest.BodyPublishers.ofString(testBody))
   .build();

HttpResponse<String> response = client.send(request,HttpResponse.BodyHandlers.ofString());