Issue
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());
}
Solution
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);
}
Answered By - viking
Answer Checked By - Timothy Miller (JavaFixing Admin)