该系列文章翻译自https://www.baeldung.com/mockito-series
Mockito默认的机制是遇到第一个校验错误就停止,也就是通常所说的fail-fast。但是,有时候我们需要执行所有的校验,并看到所有的校验结果,不管中途是否发生校验错误。VerificationCollector就是可以解决上述问题的一种Junit 规则,它可以收集测试方法中所有的校验结果。
1. Maven依赖
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.21.0</version>
</dependency>
2. fail-fast的方式
@Test
public void testLazyVerification1() throws Exception {
List mockList = mock(ArrayList.class);
verify(mockList).add("one");
verify(mockList).clear();
}
@Test
public void testLazyVerification2() throws Exception {
List mockList = mock(ArrayList.class);
verify(mockList).add("one");
verify(mockList).clear();
}
fail-fast的方式中,testLazyVerification1()和testLazyVerification2()都只能看到第一个校验的报告
Wanted but not invoked:
arrayList.add("one");
-> at com.baeldung.mockito.java8.LazyVerificationTest.testLazyVerification(LazyVerificationTest.java:19)
Actually, there were zero interactions with this mock.
3. lazy vertification的方式
@Rule
public VerificationCollector verificationCollector = MockitoJUnit.collector();
@Test
public void testLazyVerification1() throws Exception {
List mockList = mock(ArrayList.class);
verify(mockList).add("one");
verify(mockList).clear();
}
@Test
public void testLazyVerification2() throws Exception {
List mockList = mock(ArrayList.class);
verify(mockList).add("one");
verify(mockList).clear();
}
lazy vertification的方式中,可以看到所有校验的校验结果
org.mockito.exceptions.base.MockitoAssertionError: There were multiple verification failures:
1. Wanted but not invoked:
arrayList.add("one");
-> at com.baeldung.mockito.java8.LazyVerificationTest.testLazyVerification(LazyVerificationTest.java:21)
Actually, there were zero interactions with this mock.
2. Wanted but not invoked:
arrayList.clear();
-> at com.baeldung.mockito.java8.LazyVerificationTest.testLazyVerification(LazyVerificationTest.java:22)
Actually, there were zero interactions with this mock.