Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
tttppp Avatar asked Oct 15 '10 07:10

tttppp


3 Answers

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

Mockito.verify(mockMyObject).
  myMethod(
    Mockito.matches("(.*apple.*banana.*)|(.*banana.*apple.*)"
  )
);
like image 136
Boris Pavlović Avatar answered Nov 01 '22 09:11

Boris Pavlović


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

like image 23
Torsten Avatar answered Nov 01 '22 11:11

Torsten


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"));
like image 15
ferengra Avatar answered Nov 01 '22 11:11

ferengra