[英]when testing a class, check the work inside the method using a Junit and a Mockito
I have a class that I cover with tests, I am having difficulties, how can I check that inside a method addBeginList(), the operation "list.add (int)" occurs on a specific list.我有一个 class 测试,我遇到了困难,如何检查方法 addBeginList() 中的操作“list.add (int)”是否发生在特定列表上。 Using the Moсkito library, check that a specific method was called on a list in a class?
使用 Moсkito 库,检查是否在 class 的列表中调用了特定方法?
public class ClassA implements IClassA {
private List<Integer> list;
public ClassA (List<Integer> list) {
this.list = list;
}
@Override
public int addBeginList() {
long t1 = System.currentTimeMillis();
list.add(5);
long t2 = System.currentTimeMillis();
return (int) t2 - (int) t1;
}
Test class测试 class
@RunWith(MockitoJUnitRunner.class)
public class ClassATest{
private ClassA mockClassA;
private static final int EXPECTED = 0;
private static final int DELTA = 1000;
private static final int SIZE = 7000;
@Before
public void setUp() throws Exception {
mockClassA = Mockito.mock(ClassA.class);
mockClassA.initialize(SIZE);
mockClassA.addBeginList();
}
@Test
public void initialize() {
}
@Test
public void addBeginList() {
assertEquals(EXPECTED, mockClassA.addBeginList(), DELTA);
}
First step is to make sure to test the real instance of the ClassA, not a mock.第一步是确保测试 ClassA 的真实实例,而不是模拟。
Next you can either supply to it a real list and check that it contains a certain element after, or you supply it with a mocked list and check with Mockito that specific method was called:接下来,您可以向它提供一个真实列表并检查它是否包含某个元素,或者向它提供一个模拟列表并使用 Mockito 检查是否调用了特定方法:
verify(mockedList).add(5)
I found a solution to my problem:我找到了解决问题的方法:
public class ClassA extends AbstractList<Integer> implements IClassA {///}
In test class:在测试 class 中:
private List<Integer> mockedList;
private ClassA classA;
@Before
public void setUp() throws Exception {
mockedList = Mockito.mock(ClassA.class);
classA = new ClassA(mockedList);
}
@Test
public void addBeginList() {
assertEquals(EXPECTED, classA.addBeginList(), DELTA);
verify(mockedList).add(5);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.