在mockito中,我们可以捕获可能被多次调用的方法的参数,如下所示:
verify(mocked, atLeastOnce())
.myMethod(myCaptor.capture());
Run Code Online (Sandbox Code Playgroud)
然后
myCaptor.getAllValues()
Run Code Online (Sandbox Code Playgroud)
但是,然后我需要筛选所有捕获的值以找到我感兴趣的值进行验证。
我想做的是这样的:
private class IsMySpecialArg extends ArgumentMatcher<Object> {
public boolean matches(Object other) {
// Matching condition
}
}
Run Code Online (Sandbox Code Playgroud)
...
verify(mocked, atLeastOnce())
.myMethod(myCaptor.capture(argThat(new IsMySpecialArg()));
Run Code Online (Sandbox Code Playgroud)
这样我就可以简单地打电话myCaptor.getValue()
并确保它指的是我真正有兴趣捕获的论点。实现这一目标的最佳方法是什么mockito
?它是否受支持,或者我的测试策略是否存在根本性错误?
我在编写测试时经常使用 ArgumentMatchers。以下是验证传递给模拟对象的参数时可以执行的操作的示例:
private static class ExpectationArgumentMatcher extends ArgumentMatcher<String> {
private final List<String> expectedArguments;
public ExpectationArgumentMatcher(List<String> expectedArguments) {
this.expectedArguments = expectedArguments;
}
public ExpectationArgumentMatcher() {
this(new ArrayList<javax.swing.Action>());
}
@Override
public boolean matches(Object argument) {
if (argument instanceof String) {
String actualArgument = (String) argument;
return expectedArguments.contains(actualArgument);
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
显然,您期望的参数可能只是一个字符串,或更复杂的东西,但您基本上是在检查您的模拟是否是通过与您期望的参数相匹配的参数来调用的。
归档时间: |
|
查看次数: |
1679 次 |
最近记录: |