繁体   English   中英

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

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

我正在尝试模拟此 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));
    }

当我尝试下面的代码时,

    @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());
        ...
    }

我在行中收到 java.lang.NullPointerException

when(httpResponse.getEntity().getContent()).thenReturn(stream);

有人可以帮助我了解我到底错过了什么吗?

由于httpResponse.getEntity()没有配置 mocking 行为,您得到的是返回 null 的默认行为

尝试这个

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
InputStream stream;

所以你的模拟也会返回模拟。

老实说,这不是单元测试的候选者,而是集成测试,因为几乎没有要测试的代码。 我会模拟 web 服务器并检查它是否在真实的请求和响应中表现正确(例如使用 WireMock)。

现在,如果您通过使用不同的 http 客户端实现来更改内部实现,您将导致测试中断,而公共合同是相同的,因此它应该不会失败。 结果,这样的测试将阻止任何可能改进的更改,而不是通过保证(这是一个词吗?)尽管内部实施发生变化但合同保持不变来鼓励它(这是编写测试 imo 的核心原因)

暂无
暂无

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

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