tttppp
tttppp

Reputation: 8193

How to check if a parameter contains two substrings using Mockito?

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?

Upvotes: 44

Views: 43451

Answers (5)

Peto
Peto

Reputation: 33

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)

Upvotes: 3

Torsten
Torsten

Reputation: 989

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

Upvotes: 27

Eric
Eric

Reputation: 196

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"))));

Upvotes: 9

Boris Pavlović
Boris Pavlović

Reputation: 64632

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

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

Upvotes: 45

ferengra
ferengra

Reputation: 159

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"));

Upvotes: 15

Related Questions