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

如何Mock入参固定/硬编码的方法?Mockito模拟遇空指针异常

问题原因及解决办法

1. 语法错误:括号不匹配

你的when语句缺少闭合右括号,这会直接导致运行时异常,修正为:

when(b.execute(anyInt())).thenReturn(1);

2. 测试方法缺少返回值类型

doStuffTest方法未声明返回值,JUnit测试方法需显式指定void:

@Test
void doStuffTest(){
   // ... 测试逻辑
}

3. 确认Mockito静态方法的正确导入

确保anyInt()、when()、thenReturn()等静态方法已正确导入,避免隐式错误:

import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;

修正后的完整测试代码

@ExtendWith(MockitoExtension.class)
public class ATest{
  @InjectMocks
  A a;
  @Mock
  B b;

  @Test
  void doStuffTest(){
   when(b.execute(anyInt())).thenReturn(1);
   assertEquals(1,a.doStuff());
 }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:40:19