Java 如何使用 Mockito 检查参数是否包含两个子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3940301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a parameter contains two substrings using Mockito?
提问by tttppp
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?
我想修改它以检查参数是否同时包含"apple"
和"banana"
。我该怎么办?
采纳答案by Boris Pavlovi?
Just use Mockito.matches(String)
, for example:
只需使用Mockito.matches(String)
,例如:
Mockito.verify(mockMyObject).
myMethod(
Mockito.matches("(.*apple.*banana.*)|(.*banana.*apple.*)"
)
);
回答by ferengra
I think the easiest solution is to call the verify() multiple times:
我认为最简单的解决方案是多次调用 verify() :
verify(emailService).sendHtmlMail(anyString(), eq(REPORT_TITLE), contains("Client response31"));
verify(emailService).sendHtmlMail(anyString(), eq(REPORT_TITLE), contains("Client response40"));
verify(emailService, never()).sendHtmlMail(anyString(), anyString(), contains("Client response30"));
回答by Torsten
Since Java 8 and Mockito 2.1.0, it is possible to use Streams as follows:
从 Java 8 和 Mockito 2.1.0 开始,可以按如下方式使用 Streams:
Mockito.verify(mockMyObject).myMethod(
Mockito.argThat(s -> s.contains("apple") && s.contains("banana"))
);
thus improving readability
从而提高可读性
回答by Eric
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
也许这不再相关,但我找到了另一种方法,按照 Torsten answer 和 this other answer。就我而言,我使用了 Hamcrest Matchers
Mockito.verify(mockMyObject).myMethod(
Mockito.argThat(Matchers.allOf(
Matchers.containsString("apple"),
Matchers.containsString("banana"))));