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()自然触发空指针异常。
修复步骤
- 新增
HttpEntity的Mock对象 - 先指定
httpResponse.getEntity()返回这个Mock实体 - 再指定实体的
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
相关产品推荐
相关产品推荐

