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

Do Mock objects get reset for each test?(每次测试都会重置 Mock 对象吗?)
本文介绍了每次测试都会重置 Mock 对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用 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.

这篇关于每次测试都会重置 Mock 对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)