每次测试都会重置 Mock 对象吗?

2022-01-14 00:00:00 mockito java junit

我正在使用 Mockito 框架在我的 JUnit 测试中创建 Mock 对象.每个 mock 都知道它调用了哪些方法,所以在我的测试中我可以编写

I'm using the Mockito framework to create Mock objects in my JUnit tests. Each mock knows what methods have been called on it, so during my tests I can write

verify(myMock, atLeastOnce()).myMethod();

我想知道这种内部模拟知识是否会在我的测试中持续存在?如果它确实持续存在,那么在两个测试中使用相同的 verify 方法时我可能会得到误报.

I am wondering if this internal mock knowledge of what it has called will persist across my tests? If it does persist, then I could be getting false positives when using the same verify method in two tests.

代码示例

@RunWith(MockitoJUnitRunner.class)
public class EmrActivitiesImplTest {
    
    @Mock private MyClass myMock;
    
    @Before
    public void setup() {
        when(myMock.myMethod()).thenReturn("hello");
    }
    
    @Test
    public void test1() {
        // ..some logic
        verify(myMock, atLeastOnce()).myMethod();
    }
    
    @Test
    public void test2() {
        // ..some other logic
        verify(myMock, atLeastOnce()).myMethod();
    }  
}

模拟状态保持不变 - test2 无论如何都会通过,因为 test1 的验证方法通过了

Mock state is persisted - test2 will pass regardless, since test1's verify method passed

模拟状态已重置 - 如果未调用 myMock.myMethod(),test2 将失败

Mock state is reset - test2 will fail if myMock.myMethod() isn't called

推荐答案

JUnit 每次运行新的测试方法时都会创建一个新的测试类实例,并且每次创建一个新的测试方法时都会运行 @Before 方法新的测试班.您可以轻松地对其进行测试:

JUnit creates a new instance of test class each time it runs a new test method and runs @Before method each time it creates a new test class. You can easily test it:

@Before
public void setup() {
    System.out.println("setup");
    when(myMock.myMethod()).thenReturn("hello");
}

并且 MockitoJUnitRunner 将为每个测试方法创建一个新的 MyMock 模拟实例.

And MockitoJUnitRunner will create a new MyMock mock instance for every test method.

相关文章