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());
}
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
....
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With