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

如何用Mockito模拟GenericService中的WebMethod方法

解决Mockito测试GenericService时的空指针问题

问题分析

你的代码有两个核心问题导致空指针或运行错误:

  1. 被测类的service字段未注入mock对象:你创建了serviceMock,但没把它赋值给被测类中的service成员变量,导致调用service.exists()时触发空指针异常。
  2. 返回值类型不匹配:GenericService.exists()方法返回的是GenericExists对象,不是boolean,直接写thenReturn(true)会因为类型不兼容出错。

正确的测试代码示例

假设你的被测类叫CodeValidator,内部包含GenericService service字段,以下是完整的TestNG+Mockito测试代码:

import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;

public class CodeValidatorTest {

    // 被测类实例,Mockito会自动注入@Mock标记的对象
    @InjectMocks
    private CodeValidator codeValidator;

    // 要mock的GenericService接口实例
    @Mock
    private GenericService serviceMock;

    // 要mock的exists方法返回对象
    @Mock
    private GenericExists genericExistsResponse;

    @BeforeMethod
    public void setUp() {
        // 初始化Mockito注解,创建mock对象并完成注入
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void testIsValidCode_ReturnsTrue_WhenCodeExists() {
        // 设定mock行为:调用exists时返回预设的GenericExists对象,且该对象标记编码存在
        when(serviceMock.exists(any(CodeInput.class))).thenReturn(genericExistsResponse);
        when(genericExistsResponse.isExists()).thenReturn(true);

        // 执行被测方法
        boolean result = codeValidator.isValidCode("TEST_CODE");

        // 验证结果符合预期
        assertEquals(result, true);
    }

    @Test
    public void testIsValidCode_ReturnsFalse_WhenCodeDoesNotExist() {
        when(serviceMock.exists(any(CodeInput.class))).thenReturn(genericExistsResponse);
        when(genericExistsResponse.isExists()).thenReturn(false);

        boolean result = codeValidator.isValidCode("INVALID_CODE");

        assertEquals(result, false);
    }
}

关键注意事项

  • 如果被测类的service字段是私有且无setter方法,用@InjectMocks自动注入即可;如果有setter,也可以手动调用codeValidator.setService(serviceMock)完成注入。
  • 必须根据GenericExists的实际方法(比如示例中的isExists())来设定返回值,因为isValidCode最终是依赖这个方法的返回值来确定自己的结果。
  • 不要省略MockitoAnnotations.openMocks(this)步骤,它负责初始化所有@Mock标记的对象,并完成向@InjectMocks实例的注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 20:02:42