如何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
相关产品推荐
相关产品推荐

