模拟对象会在每次测试时重置吗? [英] Do Mock objects get reset for each test?

查看:86
本文介绍了模拟对象会在每次测试时重置吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Mockito框架在我的JUnit测试中创建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();
    }  
}

模拟状态保持不变-由于test1的验证方法已通过,因此无论test2将通过

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每次运行新的测试方法时都会创建一个新的测试类实例,并且每次创建一个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.

这篇关于模拟对象会在每次测试时重置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆