42

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?

1

5 Answers 5

45

Just use Mockito.matches(String), for example:

Mockito.verify(mockMyObject).
  myMethod(
    Mockito.matches("(.*apple.*banana.*)|(.*banana.*apple.*)"
  )
);
25

Since Java 8 and Mockito 2.1.0, it is possible to use Streams as follows:

Mockito.verify(mockMyObject).myMethod(
    Mockito.argThat(s -> s.contains("apple") && s.contains("banana"))
);

thus improving readability

3
  • 1
    While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
    – Alexander
    Feb 19, 2019 at 17:28
  • 1
    Thanks - this looks like a useful and more up-to-date answer. I asked this question 9 years ago, and so it might be worth mentioning the versions of Java (e.g. Java 8 streams) and/or Mockito (the docs mention this interface changed in 2.1.0: static.javadoc.io/org.mockito/mockito-core/2.24.5/org/mockito/… ).
    – tttppp
    Feb 26, 2019 at 10:41
  • 1
    Since Java 9 it could be written even shorter: Mockito.argThat(s -> List.of("apple", "banana").contains(s)). Sep 5, 2019 at 6:16
15

I think the easiest solution is to call the verify() multiple times:

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"));
1
  • 2
    I do not agree with your answer because it could be different method calls and you could not know it for sure. FYI I did not vote your answer down. Feb 25, 2020 at 10:26
9

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.verify(mockMyObject).myMethod(
   Mockito.argThat(Matchers.allOf(
      Matchers.containsString("apple"),
      Matchers.containsString("banana"))));
2

You can also use Mockito's AdditionalMatchers:

Mockito.verify(mockMyObject).myMethod(
AdditionalMatchers.and(Mockito.contains("apple"), Mockito.contains("banana")));

More info https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/AdditionalMatchers.html#and(T,T)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.