简体   繁体   中英

How can I mock HTTPResponse interface in Java with ObjectMapper

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM