Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create webclient unit tests with Junit and Mockito?

How can I create a unit test of this private method returning void using Junit4 and Mockito?

    private void fetchToken() {
        try {
        webClientBuilder.build().post().uri("http://localhost:8082/token")
                    .headers(httpHeaders -> httpHeaders.setBasicAuth("anyusername", "password")).retrieve()
                    .bodyToMono(Token.class).block();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }

like image 542
Andres Avatar asked Oct 27 '25 05:10

Andres


2 Answers

A cleaner and less fragile approach is don't mock WebClient but mock the external API using tools WireMock or MockWebServer.

I usually used MockWebServer. You may say it is an integration test but not the unit test. But it term of speed , MockWebServer is very fast just like unit test. Moreover, it allows you to use the real WebClient instance to really exercise the full HTTP stack and you can be more confident that you are testing everything.

You can do something like :

public class SomeTest {
    
    
    private MockWebServer server;

    @Test
    public void someTest(){

        MockWebServer server = new MockWebServer();
        server.start();
        HttpUrl baseUrl = server.url("/token");

        //stub the server to return the access token response
        server.enqueue(new MockResponse().setBody("{\"access_token\":\"ABC\"}"));

       //continues execute your test
        ....

    }


}
like image 98
Ken Chan Avatar answered Oct 28 '25 19:10

Ken Chan


Using mockito like that

    @Mock
    private WebClient webClient;
    @Mock
    private WebClient.RequestBodyUriSpec uriSpec;
    @Mock
    private WebClient.RequestBodyUriSpec headerSpec;


    @Test
    void someTest(){
            WebClient.RequestBodyUriSpec bodySpec = mock(WebClient.RequestBodyUriSpec.class);
            WebClient.ResponseSpec response = mock(WebClient.ResponseSpec.class);
    
            when(webClient.post()).thenReturn(uriSpec);
            when(uriSpec.uri(uri)).thenReturn(headerSpec);
            doReturn(bodySpec).when(headerSpec).bodyValue(body);
            when(bodySpec.retrieve()).thenReturn(response);
    }

like image 28
viking Avatar answered Oct 28 '25 18:10

viking



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!