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

Mockito测试遇WrongTypeOfReturnValue错误,修复尝试失败求助

错误原因分析

  1. 初始WrongTypeOfReturnValue错误:你mock的HttpEntity对象的getContent()方法未被桩(Stub),当执行EntityUtils.toString(httpEntity)时,内部会调用httpEntity.getContent(),而Mockito对未Stub的方法默认返回null,但该方法声明需返回InputStream,类型不匹配触发报错。
  2. 静态方法mock方式错误:EntityUtils.toString是静态方法,Mockito常规语法不支持直接mock静态方法,你尝试的doReturn写法不符合静态mock的规范,因此出现编译错误或UnfinishedStubbingException。

解决方案

方案一:Stub HttpEntity的getContent()方法(推荐,避免静态mock)

无需mock静态方法,直接让mock的HttpEntity返回合法的InputStream,让EntityUtils.toString正常执行:

@Test
public void geocode() throws Exception {
    Mockito.when(httpClient.execute(any())).thenReturn(httpResponse);
    Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
    
    // 关键:为HttpEntity的getContent()方法返回包含测试字符串的InputStream
    String testContent = "test_string";
    Mockito.when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(testContent.getBytes()));
    
    String result = appService.calculate("param string", "json", "key");

    Assert.assertEquals("test_string", result);
}

方案二:使用Mockito静态mock(需Mockito 3.4.0+)

若必须mock静态方法EntityUtils.toString,需使用mockStatic,同时要引入mockito-inline依赖(默认mockito-core不支持静态mock):

依赖调整(Maven示例)
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>4.8.1</version>
    <scope>test</scope>
</dependency>
修改测试代码
@Test
public void geocode() throws Exception {
    Mockito.when(httpClient.execute(any())).thenReturn(httpResponse);
    Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
    
    // 使用try-with-resources管理静态mock的生命周期,避免全局影响
    try (MockedStatic<EntityUtils> mockedEntityUtils = Mockito.mockStatic(EntityUtils.class)) {
        mockedEntityUtils.when(() -> EntityUtils.toString(httpEntity)).thenReturn("test_string");
        
        String result = appService.calculate("param string", "json", "key");

        Assert.assertEquals("test_string", result);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:35:14