Do Mock objects get reset for each test?(每次测试都会重置 Mock 对象吗?)
问题描述
我正在使用 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 对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:每次测试都会重置 Mock 对象吗?


基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01