I am trying to mock this HTTPResponse interface, where I am getting an error
public Product handleSolrRequest(CloseableHttpClient client,String query,String limit) throws URISyntaxException, IOException {
HttpGet request = new HttpGet(SolrSchemaUtil.generateURI(solrURL, query, limit));
return client.execute(request, httpResponse ->
mapper.readValue(httpResponse.getEntity().getContent(), Product.class));
}
when I tried the below code,
@Mock
HttpResponse httpResponse;
@Mock
ObjectMapper mockMapper;
@Mock
InputStream stream;
@BeforeMethod
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testHandleSolrRequest() throws IOException, URISyntaxException {
when(httpResponse.getEntity().getContent()).thenReturn(stream);
when(mockMapper.readValue(eq(stream), Product.class))
.thenReturn(TestUtil.createSolrProductRS());
...
}
I am getting java.lang.NullPointerException, in the line
when(httpResponse.getEntity().getContent()).thenReturn(stream);
Can someone please help me in understanding what exactly am I missing?
CodePudding user response:
Since httpResponse.getEntity()
has no mocking behavior configured, you got the default one which is returning null
Try this
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
InputStream stream;
so your mock will returns mocks as well.
To be honest this one is not a candidate to unit testing but rather integration testing since there is almost NO CODE OF YOURS to test. I would mock web server and check if it behaves correctly with the real request and response (eg using WireMock).
Right now, if you change internal implementation by eg using different http client implementation, you will cause the tests to break, while the public contaract is the same so it should not fail. As a result, such test will discourage any potentially improving changes, instead encouraging it by guaranteeing (is that a word?) that the contract stays intact despite change internal imlementation (this is the core reason of writing tests imo)