简体   繁体   English

如何在 JUnit 测试中使用 Mockito?

[英]How to use Mockito in JUnit test?

The class to test is a self-made LinkedList.要测试的类是一个自制的 LinkedList。 In one specific method, I just want to use Mockito to avoid adding extra element to the list , that could affect other test methods.在一种特定的方法中,我只想使用 Mockito 来避免向列表中添加额外的元素,这可能会影响其他测试方法。 But I don't believe I use it in a right way.但我不相信我以正确的方式使用它。 Any suggestions?有什么建议?

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);
}

} }

In your tests, you are only testing a mock, but not your class.在你的测试中,你只是在测试一个模拟,而不是你的班级。 For what you mentioned, just change the setup method to instantiate the real class.对于您提到的内容,只需更改 setup 方法以实例化真正的类。

@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);
}

Before each test, the setup method is called, so you'll have a fresh list with the 4 elements in it.在每次测试之前,都会调用 setup 方法,因此您将拥有一个包含 4 个元素的新列表。

Mocks are used when the class that is being tested uses collaborators.当被测试的类使用协作者时使用模拟。 The idea behind is to isolate the class, so you are sure that any error comes from the class under test and not a collaborator.背后的想法是隔离类,因此您可以确定任何错误都来自被测类而不是协作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM