我开始学习junits,我正在尝试模拟arraylist类,但它向我显示空指针异常。
这是我的代码:
public class MyListTest {
@Mock
ArrayList<String> al;
@Test
public void whenNotUseMockAnnotation_thenCorrect() {
when(al.add("a")).thenReturn(true);
assertTrue(al.add("a"));
}
}
最佳答案
需要“启动”Mockito。实际上@Mock注释就像一个装饰器,你需要执行以下操作之一:
- 使用 MockitoJUnitRunner 注释 JUnit 测试:
@RunWith(MockitoJUnitRunner.class)
public class MyListTest
- 通过 MockitoAnnotations.initMocks() 以编程方式启用 Mockito。您可以在 JUnit 的 @Before 方法中使用一次。示例:
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
关于java - Junits 中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61202704/