如何使用 Mockito 检查参数是否包含两个子字符串?
我的测试中有一行目前看起来像:
Mockito.verify(mockMyObject).myMethod(Mockito.contains("apple"));
我想修改它以检查参数是否同时包含 "apple"
和 "banana"
。我该怎么办呢?
I have a line in my test that currently looks like:
Mockito.verify(mockMyObject).myMethod(Mockito.contains("apple"));
I would like to modify it to check if the parameter contains both "apple"
and "banana"
. How would I go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需使用
Mockito.matches(String)
,例如:Just use
Mockito.matches(String)
, for example:从 Java 8 和 Mockito 2.1.0 开始,可以按如下方式使用 Streams:
从而提高可读性
Since Java 8 and Mockito 2.1.0, it is possible to use Streams as follows:
thus improving readability
我认为最简单的解决方案是多次调用 verify() :
I think the easiest solution is to call the verify() multiple times:
也许这不再相关,但我找到了另一种方法来做到这一点,遵循托斯顿的答案和另一个答案。就我而言,我使用 Hamcrest 匹配器
Maybe this is not relevant anymore but I found another way to do it, following Torsten answer and this other answer. In my case I used Hamcrest Matchers
您还可以使用 Mockito 的
AdditionalMatchers
:更多信息 https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/AdditionalMatchers.html#and(T,T )
You can also use Mockito's
AdditionalMatchers
:More info https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/AdditionalMatchers.html#and(T,T)