How to combine multiple Mockito layouts with logical "and" / "or"?

I want to test the use of Mockito so that the string argument satisfies two conditions:

verify(mockClass).doSomething(Matchers.startsWith("prefix")); verify(mockClass).doSomething(Matchers.endsWith("suffix")); 

How to combine these two into one statement?

+8
mockito
source share
2 answers

This is possible with org.mockito.AdditionalMatchers :

 import static org.mockito.AdditionalMatchers.and; verify(mockClass).doSomething( and(Matchers.startsWith("prefix"), Matchers.endsWith("suffix")); 

There are also org.mockito.AdditionalMatchers.or and org.mockito.AdditionalMatchers.not .

+18
source share

Previous comments have caused that and accepts only two arguments, and that an option that takes three or more will be beneficial. The following code solves this recursively, allowing you to specify multiple patterns in varargs:

 public static String conjunction(String... matchers) { if (matchers.length < 2) { throw new IllegalArgumentException("matchers.length must be >= 2"); } else if (matchers.length == 2) { return and(matchers[0], matchers[1]); } else { final String[] tail = new String[matchers.length - 1]; System.arraycopy(matchers, 1, tail, 0, tail.length); return and(matchers[0], conjunction(tail)); } } 

subject to the following imports:

 import static org.mockito.AdditionalMatchers.*; import static org.mockito.Mockito.*; 
0
source share

All Articles