argThat加lambda
这就是你的论证验证失败的原因:
verify(mock).mymethod(argThat(
x -> false ));
在哪里
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
argThat 加断言
上面的测试会“说”Expected: lambda$... Was: YourClass.toSting...。如果在 lambda 中使用断言,您可以获得更具体的失败原因:
verify(mock).mymethod(argThat( x -> {
assertThat(x).isNotNull();
assertThat(x.description).contains("KEY");
return true;
}));
❗️但是❗️:只有在
- 预计会调用 1 次,或者
- 预计调用 2 次以上,但验证器始终匹配(返回
true)。
如果验证的方法调用了 2 次以上,mockito 会将所有调用的组合传递给每个验证者。所以 mockito 期望您的验证器为参数集之一静默返回 true,并为其他有效调用返回 false(无断言异常)。这种期望对于 1 次方法调用来说不是问题 - 它应该只返回 true 1 次。
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
现在失败的测试将显示:Expected: Obj.description to contain 'KEY'. Was: 'Actual description'。注意:我使用了assertJ 断言,但使用哪个断言框架取决于您。
直接参数
Mokito 使用 equals() 比较直接参数:
verify(mock).mymethod(expectedArg);
// NOTE: ^ where the parentheses must be closed.
eq匹配器
argThat 带有多个参数。
如果您使用argThat,则必须为所有参数提供匹配项。例如。如果,在不同的情况下,你有另一个带有 2 个参数的方法:
verify(mock).mymethod2(eq("VALUE_1"), argThat((x)->false));
// above is correct as eq() is also an argument matcher.
verify(mock).mymethod2("VALUE_1", argThat((x)->false));
// above is incorrect; an exception will be thrown, as the first arg. is given without an argument matcher.
地点:
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
原始问题失败的根本原因是括号的错误位置:
-
verify(mock.mymethod...。那是错误的。正确的是:
verify(mock).*