I have the following class that I want to unit test:
@RequiredArgsConstructor
@Service
public class Service {
private final WebClient.Builder builder;
private WebClient webClient;
@PostConstruct
public void init() {
searchUri = "/search-uri";
webClient = builder.baseUrl(searchUri)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
public ResponseSpec search() {
return webClient
.get()
.uri(uriBuilder ->
uriBuilder
.path("/search-uri")
// alot of query param, not important
.build()
)
.accept(MediaType.APPLICATION_JSON)
.acceptCharset(StandardCharsets.UTF_8)
.retrieve();
}
}
This is my test class:
@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class ServiceTest {
@InjectMocks
private Service service;
@Mock
private WebClient webClient;
@Mock
private Builder builder;
@Test
public void testSearch() {
when(builder.baseUrl(Mockito.anyString())).thenReturn(builder);
when(builder.defaultHeader(Mockito.anyString(), Mockito.anyString())).thenReturn(builder);
when(builder.build()).thenReturn(webClient);
issuerServiceImpl.init();
WebClient.RequestHeadersUriSpec uriSpecMock = mock(WebClient.RequestHeadersUriSpec.class);
WebClient.RequestHeadersSpec headersSpecMock = mock(WebClient.RequestHeadersSpec.class);
WebClient.ResponseSpec responseSpecMock = mock(WebClient.ResponseSpec.class);
when(webClient.get()).thenReturn(uriSpecMock);
lenient().when(uriSpecMock.uri(Mockito.any(URI.class))).thenReturn(headersSpecMock);
issuerServiceImpl.searchIssuers("");
}
}
An exception (NullPointerException
) happens in the line of .accept(MediaType.APPLICATION_JSON)
because the uri()
returns null and the code tries to call method .accept()
on a null object.
I am not let to change the Service
class. I can change only my test class. Not sure how could I make it to work.
Aucun commentaire:
Enregistrer un commentaire