如何在Mockito中使用软断言? [英] How to use soft assertions in Mockito?
问题描述
我知道我们可以使用 ErrorCollector
或没有断言的软断言(AssertJ或TestNG)立即使单元测试失败.
I know that we can use ErrorCollector
or soft assertions (AssertJ or TestNG) that do not fail a unit test immediately.
它们如何与Mockito断言一起使用?还是如果他们不能,Mockito是否提供其他选择?
How they can be used with Mockito assertions? Or if they can't, does Mockito provide any alternatives?
verify(mock).isMethod1();
verify(mock, times(1)).callMethod2(any(StringBuilder.class));
verify(mock, never()).callMethod3(any(StringBuilder.class));
verify(mock, never()).callMethod4(any(String.class));
问题
在此代码段中,如果验证失败,则测试将失败,这将中止其余的verify
语句(它可能需要多次测试运行,直到揭示此单元测试的所有失败为止,这是时间-消费).
Problem
In this snippet of code if a verification will fail, then the test will fail which will abort the remaining verify
statements (it may require multiple test runs until all the failures from this unit test are revealed, which is time-consuming).
推荐答案
Since Mockito 2.1.0 you can use VerificationCollector rule in order to collect multiple verification failures and report at once.
import static org.mockito.Mockito.verify;
import org.junit.Rule;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.VerificationCollector;
// ...
@Rule
public final VerificationCollector collector = MockitoJUnit.collector();
@Test
public void givenXWhenYThenZ() throws Exception {
// ...
verify(mock).isMethod1();
verify(mock, times(1)).callMethod2(any(StringBuilder.class));
verify(mock, never()).callMethod3(any(StringBuilder.class));
verify(mock, never()).callMethod4(any(String.class));
}
已知问题
此规则不能与 ErrorCollector
相同测试方法中的规则.在单独的测试中,它工作正常.
Known issues
This rule cannot be used with ErrorCollector
rule in the same test method. In separate tests it works fine.
这篇关于如何在Mockito中使用软断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!