Class Matchers
- Direct Known Subclasses:
Mockito
AdditionalMatchers.
Mockito extends Matchers so to get access to all matchers just import Mockito class statically.
//stubbing using anyInt() argument matcher
when(mockedList.get(anyInt())).thenReturn("element");
//following prints "element"
System.out.println(mockedList.get(999));
//you can also verify using argument matcher
verify(mockedList).get(anyInt());
Scroll down to see all methods - full list of matchers.
Warning:
If you are using argument matchers, all arguments have to be provided by matchers.
E.g: (example shows verification but the same applies to stubbing):
verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
//above is correct - eq() is also an argument matcher
verify(mock).someMethod(anyInt(), anyString(), "third argument");
//above is incorrect - exception will be thrown because third argument is given without argument matcher.
Matcher methods like anyObject(), eq() do not return matchers.
Internally, they record a matcher on a stack and return a dummy value (usually null).
This implementation is due static type safety imposed by java compiler.
The consequence is that you cannot use anyObject(), eq() methods outside of verified/stubbed method.
Warning 2:
The any family methods *doesn't do any type checks*, those are only here to avoid casting
in your code. If you want to perform type checks use the isA(Class) method.
This might however change (type checks could be added) in a future major release.
Custom Argument Matchers
UseargThat(org.hamcrest.Matcher<T>) method and pass an instance of hamcrest Matcher.
Before you start implementing your own custom argument matcher, make sure you check out ArgumentCaptor api.
So, how to implement your own argument matcher?
First, you might want to subclass ArgumentMatcher which is an hamcrest matcher with predefined describeTo() method.
Default description generated by describeTo() uses decamelized class name - to promote meaningful class names.
Example:
class IsListOfTwoElements extends ArgumentMatcher<List> {
public boolean matches(Object list) {
return ((List) list).size() == 2;
}
}
List mock = mock(List.class);
when(mock.addAll(argThat(new IsListOfTwoElements()))).thenReturn(true);
mock.addAll(Arrays.asList("one", "two"));
verify(mock).addAll(argThat(new IsListOfTwoElements()));
To keep it readable you may want to extract method, e.g:
verify(mock).addAll(argThat(new IsListOfTwoElements()));
//becomes
verify(mock).addAll(listOfTwoElements());
Warning: Be reasonable with using complicated argument matching, especially custom argument matchers, as it can make the test less readable.
Sometimes it's better to implement equals() for arguments that are passed to mocks
(Mockito naturally uses equals() for argument matching).
This can make the test cleaner.
Also, sometimes ArgumentCaptor may be a better fit than custom matcher.
For example, if custom argument matcher is not likely to be reused
or you just need it to assert on argument values to complete verification of behavior.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Tany()Any object ornull.static <T> TAny kind object, not necessary of the given class.static booleanAnyboolean,Booleanornull.static byteanyByte()Anybyte,Byteornull.static charanyChar()Anychar,Characterornull.static CollectionAnyCollectionornull.static <T> Collection<T> anyCollectionOf(Class<T> clazz) Generic friendly alias toanyCollection().static doubleAnydouble,Doubleornull.static floatanyFloat()Anyfloat,Floatornull.static intanyInt()Any int, Integer ornull.static ListanyList()AnyListornull.static <T> List<T> Generic friendly alias toanyList().static longanyLong()Anylong,Longornull.static MapanyMap()AnyMapornull.static <K,V> Map <K, V> Generic friendly alias toanyMap().static <T> TAnyObjectornull.static SetanySet()AnySetornull.static <T> Set<T> Generic friendly alias toanySet().static shortanyShort()Anyshort,Shortornull.static StringAnyStringornull.static <T> TAny vararg, meaning any number and values of arguments.static <T> TargThat(org.hamcrest.Matcher<T> matcher) Allows creating custom argument matchers.static booleanbooleanThat(org.hamcrest.Matcher<Boolean> matcher) Allows creating customBooleanargument matchers.static byteAllows creating customByteargument matchers.static charAllows creating customCharacterargument matchers.static StringStringargument that contains the given substring.static doubledoubleThat(org.hamcrest.Matcher<Double> matcher) Allows creating customDoubleargument matchers.static StringStringargument that ends with the given suffix.static booleaneq(boolean value) booleanargument that is equal to the given value.static byteeq(byte value) byteargument that is equal to the given value.static chareq(char value) charargument that is equal to the given value.static doubleeq(double value) doubleargument that is equal to the given value.static floateq(float value) floatargument that is equal to the given value.static inteq(int value) intargument that is equal to the given value.static longeq(long value) longargument that is equal to the given value.static shorteq(short value) shortargument that is equal to the given value.static <T> Teq(T value) Object argument that is equal to the given value.static floatAllows creating customFloatargument matchers.static intAllows creating customIntegerargument matchers.static <T> TObjectargument that implements the given class.static ObjectNotnullargument.static <T> TNotnullargument, not necessary of the given class.static ObjectisNull()nullargument.static <T> Tnullargument.static longAllows creating customLongargument matchers.static StringStringargument that matches the given regular expression.static ObjectnotNull()Notnullargument.static <T> TNotnullargument, not necessary of the given class.static <T> TObject argument that is reflection-equal to the given value with support for excluding selected fields from a class.static <T> Tsame(T value) Object argument that is the same as the given value.static shortAllows creating customShortargument matchers.static StringstartsWith(String prefix) Stringargument that starts with the given prefix.
-
Constructor Details
-
Matchers
public Matchers()
-
-
Method Details
-
anyBoolean
public static boolean anyBoolean()Anyboolean,Booleanornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
false.
-
anyByte
public static byte anyByte()Anybyte,Byteornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
0.
-
anyChar
public static char anyChar()Anychar,Characterornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
0.
-
anyInt
public static int anyInt()Any int, Integer ornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
0.
-
anyLong
public static long anyLong()Anylong,Longornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
0.
-
anyFloat
public static float anyFloat()Anyfloat,Floatornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
0.
-
anyDouble
public static double anyDouble()Anydouble,Doubleornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
0.
-
anyShort
public static short anyShort()Anyshort,Shortornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
0.
-
anyObject
public static <T> T anyObject()AnyObjectornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
Has aliases:
any()andany(Class clazz)See examples in javadoc for
Matchersclass- Returns:
null.
-
anyVararg
public static <T> T anyVararg()Any vararg, meaning any number and values of arguments.Example:
See examples in javadoc for//verification: mock.foo(1, 2); mock.foo(1, 2, 3, 4); verify(mock, times(2)).foo(anyVararg()); //stubbing: when(mock.foo(anyVararg()).thenReturn(100); //prints 100 System.out.println(mock.foo(1, 2)); //also prints 100 System.out.println(mock.foo(1, 2, 3, 4));Matchersclass- Returns:
null.
-
any
Any kind object, not necessary of the given class. The class argument is provided only to avoid casting.Sometimes looks better than
anyObject()- especially when explicit casting is requiredAlias to
anyObject()This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Parameters:
clazz- The type to avoid casting- Returns:
null.
-
any
public static <T> T any()Any object ornull.Shorter alias to
anyObject()This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
null.
-
anyString
AnyStringornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
- empty String ("")
-
anyList
AnyListornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
- empty List.
-
anyListOf
Generic friendly alias toanyList(). It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.Any
Listornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Parameters:
clazz- Type owned by the list to avoid casting- Returns:
- empty List.
-
anySet
AnySetornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
- empty Set
-
anySetOf
Generic friendly alias toanySet(). It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.Any
SetornullThis method *dones't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Parameters:
clazz- Type owned by the Set to avoid casting- Returns:
- empty Set
-
anyMap
AnyMapornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
- empty Map.
-
anyMapOf
Generic friendly alias toanyMap(). It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.Any
MapornullThis method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Parameters:
keyClazz- Type of the map key to avoid castingvalueClazz- Type of the value to avoid casting- Returns:
- empty Map.
-
anyCollection
AnyCollectionornull.This method *dones't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Returns:
- empty Collection.
-
anyCollectionOf
Generic friendly alias toanyCollection(). It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.Any
Collectionornull.This method *doesn't do any type checks*, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.
See examples in javadoc for
Matchersclass- Parameters:
clazz- Type owned by the collection to avoid casting- Returns:
- empty Collection.
-
isA
Objectargument that implements the given class.See examples in javadoc for
Matchersclass- Type Parameters:
T- the accepted type.- Parameters:
clazz- the class of the accepted type.- Returns:
null.
-
eq
public static boolean eq(boolean value) booleanargument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
0.
-
eq
public static byte eq(byte value) byteargument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
0.
-
eq
public static char eq(char value) charargument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
0.
-
eq
public static double eq(double value) doubleargument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
0.
-
eq
public static float eq(float value) floatargument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
0.
-
eq
public static int eq(int value) intargument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
0.
-
eq
public static long eq(long value) longargument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
0.
-
eq
public static short eq(short value) shortargument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
0.
-
eq
public static <T> T eq(T value) Object argument that is equal to the given value.See examples in javadoc for
Matchersclass- Parameters:
value- the given value.- Returns:
null.
-
refEq
Object argument that is reflection-equal to the given value with support for excluding selected fields from a class.This matcher can be used when equals() is not implemented on compared objects. Matcher uses java reflection API to compare fields of wanted and actual object.
Works similarly to EqualsBuilder.reflectionEquals(this, other, exlucdeFields) from apache commons library.
Warning The equality check is shallow!
See examples in javadoc for
Matchersclass- Parameters:
value- the given value.excludeFields- fields to exclude, if field does not exist it is ignored.- Returns:
null.
-
same
public static <T> T same(T value) Object argument that is the same as the given value.See examples in javadoc for
Matchersclass- Type Parameters:
T- the type of the object, it is passed through to prevent casts.- Parameters:
value- the given value.- Returns:
null.
-
isNull
nullargument.See examples in javadoc for
Matchersclass- Returns:
null.
-
isNull
nullargument. The class argument is provided to avoid casting.See examples in javadoc for
Matchersclass- Parameters:
clazz- Type to avoid casting- Returns:
null.
-
notNull
- Returns:
null.
-
notNull
Notnullargument, not necessary of the given class. The class argument is provided to avoid casting.alias to
isNotNull(Class)See examples in javadoc for
Matchersclass- Parameters:
clazz- Type to avoid casting- Returns:
null.
-
isNotNull
- Returns:
null.
-
isNotNull
Notnullargument, not necessary of the given class. The class argument is provided to avoid casting.alias to
notNull(Class)See examples in javadoc for
Matchersclass- Parameters:
clazz- Type to avoid casting- Returns:
null.
-
contains
Stringargument that contains the given substring.See examples in javadoc for
Matchersclass- Parameters:
substring- the substring.- Returns:
- empty String ("").
-
matches
Stringargument that matches the given regular expression.See examples in javadoc for
Matchersclass- Parameters:
regex- the regular expression.- Returns:
- empty String ("").
-
endsWith
Stringargument that ends with the given suffix.See examples in javadoc for
Matchersclass- Parameters:
suffix- the suffix.- Returns:
- empty String ("").
-
startsWith
Stringargument that starts with the given prefix.See examples in javadoc for
Matchersclass- Parameters:
prefix- the prefix.- Returns:
- empty String ("").
-
argThat
public static <T> T argThat(org.hamcrest.Matcher<T> matcher) Allows creating custom argument matchers.In rare cases when the parameter is a primitive then you *must* use relevant intThat(), floatThat(), etc. method. This way you will avoid
NullPointerExceptionduring auto-unboxing.See examples in javadoc for
ArgumentMatcherclass- Parameters:
matcher- decides whether argument matches- Returns:
null.
-
charThat
Allows creating customCharacterargument matchers.See examples in javadoc for
Matchersclass- Parameters:
matcher- decides whether argument matches- Returns:
0.
-
booleanThat
Allows creating customBooleanargument matchers.See examples in javadoc for
Matchersclass- Parameters:
matcher- decides whether argument matches- Returns:
false.
-
byteThat
Allows creating customByteargument matchers.See examples in javadoc for
Matchersclass- Parameters:
matcher- decides whether argument matches- Returns:
0.
-
shortThat
Allows creating customShortargument matchers.See examples in javadoc for
Matchersclass- Parameters:
matcher- decides whether argument matches- Returns:
0.
-
intThat
Allows creating customIntegerargument matchers.See examples in javadoc for
Matchersclass- Parameters:
matcher- decides whether argument matches- Returns:
0.
-
longThat
Allows creating customLongargument matchers.See examples in javadoc for
Matchersclass- Parameters:
matcher- decides whether argument matches- Returns:
0.
-
floatThat
Allows creating customFloatargument matchers.See examples in javadoc for
Matchersclass- Parameters:
matcher- decides whether argument matches- Returns:
0.
-
doubleThat
Allows creating customDoubleargument matchers.See examples in javadoc for
Matchersclass- Parameters:
matcher- decides whether argument matches- Returns:
0.
-