Testing spring webclient without spring context


Spring webclient is an important component in the spring framework. Its highly customizable, allows us to do perform all the http operations in a declarative way.





But the check is you cant unit test the spring webclient. To perform assertions you would likely need to use wiremock which takes a lot of time for the tests to initialize and run. This affects the motivation to perform the test driven development.





so i decided to write my own library which allows me to perform assertions on webclient call






public WebClient build() {
WebClient.Builder builder = this.builder
.clientConnector(
new FakeHttpConnector(requestResponsesList)
)
.exchangeFunction(ExchangeFunctionFactory.getInstance(this));

if (baseUrl != null) {
builder.baseUrl(baseUrl);
}

return builder.build();
}




The above snippet of code is from the library. I perform the assertions by writing a custom http connector and a exchange function to perform assertions.





How can i use it ?





it available via maven, add the below to the pom.xml file






<dependency>
<groupId>io.github.naveen17797</groupId>
<artifactId>fakewebclient</artifactId>
<scope>test</scope>
</dependency>




Lets say i want to test a post request to www.google.com, i could perform assertions like this





FakeWebClientBuilder fakeWebClientBuilder = FakeWebClientBuilder.useDefaultWebClientBuilder();

FakeRequestResponse fakeRequestResponse = new FakeRequestResponseBuilder()
.withRequestUrl("https://google.com/foo")
.withRequestMethod(HttpMethod.POST)
.withRequestBody(BodyInserters.fromFormData("foo", "bar"))
.replyWithResponse("test")
.replyWithResponseStatusCode(200)
.build();



WebClient client =
FakeWebClientBuilder.useDefaultWebClientBuilder()
.baseUrl("https://google.com")
.addRequestResponse(fakeRequestResponse)
.build();


assertEquals("test", client.method(HttpMethod.POST)
.uri(uriBuilder -> uriBuilder.path("/foo").build())
.body(BodyInserters.fromFormData("foo", "bar"))
.exchange().block()
.bodyToMono(String.class).block());

Assertions.assertTrue(fakeWebClientBuilder.assertAllResponsesDispatched());




simple isn't it ? No more waiting for wiremock to initialize.





If you find it helpful, you can star this repo on github





https://github.com/naveen17797/fakewebclient


Share:

0 comments:

Post a Comment