You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中用ObjectMapper模拟HttpResponse接口遇空指针异常求助

问题

尝试模拟HttpResponse接口测试handleSolrRequest方法,该方法通过CloseableHttpClient执行HttpGet请求,并用ObjectMapper将响应实体的输入流解析为Product对象。编写测试代码时,在when(httpResponse.getEntity().getContent()).thenReturn(stream);行抛出java.lang.NullPointerException。

业务代码:

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());
    ...
}
分析与解决

问题原因

httpResponse.getEntity()返回了null——你只Mock了HttpResponse对象,但没有Mock它内部的HttpEntity实例。Mockito对未指定行为的Mock方法默认返回null,因此调用httpResponse.getEntity()得到null后,再调用getContent()自然触发空指针异常。

修复步骤

  1. 新增HttpEntity的Mock对象
  2. 先指定httpResponse.getEntity()返回这个Mock实体
  3. 再指定实体的getContent()返回预设的输入流

修正后的测试代码:

@Mock
HttpResponse httpResponse;
@Mock
ObjectMapper mockMapper;
@Mock
InputStream stream;
// 新增HttpEntity的Mock实例
@Mock
HttpEntity httpEntity;

@BeforeMethod
public void init() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testHandleSolrRequest() throws IOException, URISyntaxException {
    // 先mock getEntity()返回预设的HttpEntity
    when(httpResponse.getEntity()).thenReturn(httpEntity);
    // 再mock getContent()返回stream
    when(httpEntity.getContent()).thenReturn(stream);
    
    when(mockMapper.readValue(eq(stream), Product.class))
            .thenReturn(TestUtil.createSolrProductRS());
    // 补充mock CloseableHttpClient的execute方法,指定其调用响应处理器时返回预设结果
    ...
}

额外提示:还需要MockCloseableHttpClient的execute方法,让它执行传入的响应处理器逻辑并返回预设的Product对象,才能完成完整的测试闭环。

内容的提问来源于stack exchange,提问作者Shashank Dixit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:05:36