Lazy Verification with Mockito 2 – 用Mockito 2进行懒人验证

最后修改: 2017年 11月 17日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this short tutorial, we’ll look at lazy verifications in Mockito.

在这个简短的教程中,我们将看看Mockito中的懒惰验证。

Instead of failing-fast, Mockito allows us to see all results collected and reported at the end of a test.

Mockito允许我们在测试结束时看到收集和报告的所有结果,而不是失败-快速。

2. Maven Dependencies

2.Maven的依赖性

Let’s start by adding the Mockito dependency:

让我们从添加Mockito依赖性开始。

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.21.0</version>
</dependency>

3. Lazy Verification

3.懒惰的验证

The default behavior of Mockito is to stop at the first failure i.e. eagerly – the approach is also known as fail-fast.

Mockito的默认行为是在第一次失败时停止,即急切地停止 – 这种方法也被称为失败-快速

Sometimes we might need to execute and report all verifications – regardless of previous failures.

有时我们可能需要执行并报告所有的验证–不管以前是否有失败。

VerificationCollector is a JUnit rule which collects all verifications in test methods.

VerificationCollector是一个JUnit规则,收集测试方法中的所有验证。

They’re executed and reported at the end of the test if there are failures:

它们被执行,并在测试结束时报告,如果有失败的情况。

public class LazyVerificationTest {
 
    @Rule
    public VerificationCollector verificationCollector = MockitoJUnit.collector();

    // ...
}

Let’s add a simple test:

让我们添加一个简单的测试。

@Test
public void testLazyVerification() throws Exception {
    List mockList = mock(ArrayList.class);
    
    verify(mockList).add("one");
    verify(mockList).clear();
}

When this test is executed, failures of both verifications will be reported:

当这个测试被执行时,两个验证的失败将被报告

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.

Without VerificationCollector rule, only the first verification gets reported:

如果没有VerificationCollector规则,只有第一个验证被报告。

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.

4. Conclusion

4.总结

We had a quick look at how we can use lazy verification in Mockito.

我们快速浏览了一下如何在Mockito中使用懒人验证。

Also, as always, code samples can be found over on GitHub.

此外,像往常一样,可以在GitHub上找到代码样本