简体   繁体   English

如何使用 ObjectMapper 模拟 Java 中的 HTTPResponse 接口

[英]How can I mock HTTPResponse interface in Java with ObjectMapper

I am trying to mock this HTTPResponse interface, where I am getting an error我正在尝试模拟此 HTTPResponse 接口,但出现错误

    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我在行中收到 java.lang.NullPointerException

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由于httpResponse.getEntity()没有配置 mocking 行为,您得到的是返回 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).我会模拟 web 服务器并检查它是否在真实的请求和响应中表现正确(例如使用 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.现在,如果您通过使用不同的 http 客户端实现来更改内部实现,您将导致测试中断,而公共合同是相同的,因此它应该不会失败。 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)结果,这样的测试将阻止任何可能改进的更改,而不是通过保证(这是一个词吗?)尽管内部实施发生变化但合同保持不变来鼓励它(这是编写测试 imo 的核心原因)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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