要测试的类是一个自制的LinkedList。在一种特定的方法中,我只想使用Mockito避免向列表中添加额外的元素,否则可能会影响其他测试方法。但是我不相信我以正确的方式使用它。有什么建议?
public class AppTest {
private LinkedList<Integer> link;
@Before
public void setUp() {
//just want to populate the list with 4 elements for all tests
link=mock(com.sed.MyLinkedList.LinkedList.class);
link.add(111);
link.add(222);
link.add(333);
link.add(444);
}
@Test
public void testApp() {
//add extra elements here for this specific test, shouldn't be really added to list
link.add(2, 900);
//here 'when().thenReturn()' is useless
when(link.toString()).thenReturn("[111, 222, 900, 333, 444]");
assertEquals("[111, 222, 900, 333, 444]",link.toString());
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testAppException() {
link.add(5, 900);
}
}
在测试中,您仅测试一个模拟,而没有测试您的课程。对于您提到的内容,只需更改设置方法以实例化真实的类。
@Before
public void setUp() {
//just want to populate the list with 4 elements for all tests
link = new com.sed.MyLinkedList.LinkedList();
link.add(111);
link.add(222);
link.add(333);
link.add(444);
}
在每次测试之前,都会调用setup方法,因此您将拥有一个包含4个元素的新列表。
当要测试的类使用协作者时,将使用模拟。背后的想法是隔离类,因此您可以确保任何错误都来自被测类而不是协作者。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句