All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mockito.Matchers Maven / Gradle / Ivy

/*
 * Copyright (c) 2007 Mockito contributors
 * This program is made available under the terms of the MIT License.
 */
package org.mockito;

import org.mockito.internal.matchers.*;
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
import org.mockito.internal.progress.HandyReturnValues;
import org.mockito.internal.progress.MockingProgress;
import org.mockito.internal.progress.ThreadSafeMockingProgress;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Allow flexible verification or stubbing. See also {@link AdditionalMatchers}.
 * 

* {@link 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. * *

Custom Argument Matchers

* * It is important to understand the use cases and available options for dealing with non-trivial arguments * before implementing custom argument matchers. This way, you can select the best possible approach * for given scenario and produce highest quality test (clean and maintainable). * Please read on in the javadoc for {@link ArgumentMatcher} to learn about approaches and see the examples. */ @SuppressWarnings("unchecked") public class Matchers { private static final MockingProgress MOCKING_PROGRESS = new ThreadSafeMockingProgress(); /** * Any boolean or non-null Boolean *

* See examples in javadoc for {@link Matchers} class * * @return false. */ public static boolean anyBoolean() { return reportMatcher(new InstanceOf(Boolean.class)).returnFalse(); } /** * Any byte or non-null Byte. *

* See examples in javadoc for {@link Matchers} class * * @return 0. */ public static byte anyByte() { return reportMatcher(new InstanceOf(Byte.class)).returnZero(); } /** * Any char or non-null Character. *

* See examples in javadoc for {@link Matchers} class * * @return 0. */ public static char anyChar() { return reportMatcher(new InstanceOf(Character.class)).returnChar(); } /** * Any int or non-null Integer. *

* See examples in javadoc for {@link Matchers} class * * @return 0. */ public static int anyInt() { return reportMatcher(new InstanceOf(Integer.class)).returnZero(); } /** * Any long or non-null Long. *

* See examples in javadoc for {@link Matchers} class * * @return 0. */ public static long anyLong() { return reportMatcher(new InstanceOf(Long.class)).returnZero(); } /** * Any float or non-null Float. *

* See examples in javadoc for {@link Matchers} class * * @return 0. */ public static float anyFloat() { return reportMatcher(new InstanceOf(Float.class)).returnZero(); } /** * Any double or non-null Double. *

* See examples in javadoc for {@link Matchers} class * * @return 0. */ public static double anyDouble() { return reportMatcher(new InstanceOf(Double.class)).returnZero(); } /** * Any short or non-null Short. *

* See examples in javadoc for {@link Matchers} class * * @return 0. */ public static short anyShort() { return reportMatcher(new InstanceOf(Short.class)).returnZero(); } /** * Matches anything, including null. *

* This is an alias of: {@link #any()} and {@link #any(java.lang.Class)} *

* See examples in javadoc for {@link Matchers} class * * @return null. */ public static T anyObject() { return (T) reportMatcher(Any.ANY).returnNull(); } /** * Any vararg, meaning any number and values of arguments. *

* Example: *


     *   //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));
     * 
* See examples in javadoc for {@link Matchers} class * * @return null. */ public static T anyVararg() { return (T) reportMatcher(AnyVararg.ANY_VARARG).returnNull(); } /** * Matches any object, including nulls *

* This method doesn't do type checks with the given parameter, 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 {@link Matchers} class *

* This is an alias of: {@link #any()} and {@link #anyObject()} *

* @return null. */ public static T any(Class clazz) { return (T) reportMatcher(Any.ANY).returnFor(clazz); } /** * Matches anything, including nulls *

* Shorter alias to {@link Matchers#anyObject()} *

* See examples in javadoc for {@link Matchers} class *

* This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)} *

* @return null. */ public static T any() { return anyObject(); } /** * Any non-null String *

* See examples in javadoc for {@link Matchers} class * * @return empty String ("") */ public static String anyString() { return reportMatcher(new InstanceOf(String.class)).returnString(); } /** * Any non-null List. *

* See examples in javadoc for {@link Matchers} class * * @return empty List. */ public static List anyList() { return reportMatcher(new InstanceOf(List.class)).returnList(); } /** * Generic friendly alias to {@link Matchers#anyList()}. * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings. *

* Any non-null List. *

* This method doesn't do type checks with the given parameter, 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 {@link Matchers} class * * @param clazz Type owned by the list to avoid casting * @return empty List. */ public static List anyListOf(Class clazz) { return anyList(); } /** * Any non-null Set. *

* See examples in javadoc for {@link Matchers} class * * @return empty Set */ public static Set anySet() { return reportMatcher(new InstanceOf(Set.class)).returnSet(); } /** * Generic friendly alias to {@link Matchers#anySet()}. * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings. *

* Any non-null Set. *

* This method doesn't do type checks with the given parameter, 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 {@link Matchers} class * * @param clazz Type owned by the Set to avoid casting * @return empty Set */ public static Set anySetOf(Class clazz) { return anySet(); } /** * Any non-null Map. *

* See examples in javadoc for {@link Matchers} class * * @return empty Map. */ public static Map anyMap() { return reportMatcher(new InstanceOf(Map.class)).returnMap(); } /** * Generic friendly alias to {@link Matchers#anyMap()}. * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings. *

* Any non-null Map. *

* This method doesn't do type checks with the given parameter, 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 {@link Matchers} class * * @param keyClazz Type of the map key to avoid casting * @param valueClazz Type of the value to avoid casting * @return empty Map. */ public static Map anyMapOf(Class keyClazz, Class valueClazz) { return anyMap(); } /** * Any non-null Collection. *

* See examples in javadoc for {@link Matchers} class * * @return empty Collection. */ public static Collection anyCollection() { return reportMatcher(new InstanceOf(Collection.class)).returnList(); } /** * Generic friendly alias to {@link Matchers#anyCollection()}. * It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings. *

* Any non-null Collection. *

* This method doesn't do type checks with the given parameter, 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 {@link Matchers} class * * @param clazz Type owned by the collection to avoid casting * @return empty Collection. */ public static Collection anyCollectionOf(Class clazz) { return anyCollection(); } /** * Object argument that implements the given class. *

* See examples in javadoc for {@link Matchers} class * * @param * the accepted type. * @param clazz * the class of the accepted type. * @return null. */ public static T isA(Class clazz) { return reportMatcher(new InstanceOf(clazz)).returnFor(clazz); } /** * boolean argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return 0. */ public static boolean eq(boolean value) { return reportMatcher(new Equals(value)).returnFalse(); } /** * byte argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return 0. */ public static byte eq(byte value) { return reportMatcher(new Equals(value)).returnZero(); } /** * char argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return 0. */ public static char eq(char value) { return reportMatcher(new Equals(value)).returnChar(); } /** * double argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return 0. */ public static double eq(double value) { return reportMatcher(new Equals(value)).returnZero(); } /** * float argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return 0. */ public static float eq(float value) { return reportMatcher(new Equals(value)).returnZero(); } /** * int argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return 0. */ public static int eq(int value) { return reportMatcher(new Equals(value)).returnZero(); } /** * long argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return 0. */ public static long eq(long value) { return reportMatcher(new Equals(value)).returnZero(); } /** * short argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return 0. */ public static short eq(short value) { return reportMatcher(new Equals(value)).returnZero(); } /** * Object argument that is equal to the given value. *

* See examples in javadoc for {@link Matchers} class * * @param value * the given value. * @return null. */ public static T eq(T value) { return (T) reportMatcher(new Equals(value)).returnFor(value); } /** * 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 {@link Matchers} class * * @param value * the given value. * @param excludeFields * fields to exclude, if field does not exist it is ignored. * @return null. */ public static T refEq(T value, String... excludeFields) { return reportMatcher(new ReflectionEquals(value, excludeFields)).returnNull(); } /** * Object argument that is the same as the given value. *

* See examples in javadoc for {@link Matchers} class * * @param * the type of the object, it is passed through to prevent casts. * @param value * the given value. * @return null. */ public static T same(T value) { return (T) reportMatcher(new Same(value)).returnFor(value); } /** * null argument. *

* See examples in javadoc for {@link Matchers} class * * @return null. */ public static Object isNull() { return reportMatcher(Null.NULL).returnNull(); } /** * null argument. * The class argument is provided to avoid casting. *

* See examples in javadoc for {@link Matchers} class * * @param clazz Type to avoid casting * @return null. */ public static T isNull(Class clazz) { return (T) reportMatcher(Null.NULL).returnNull(); } /** * Not null argument. *

* alias to {@link Matchers#isNotNull()} *

* See examples in javadoc for {@link Matchers} class * * @return null. */ public static Object notNull() { return reportMatcher(NotNull.NOT_NULL).returnNull(); } /** * Not null argument, not necessary of the given class. * The class argument is provided to avoid casting. *

* alias to {@link Matchers#isNotNull(Class)} *

* See examples in javadoc for {@link Matchers} class * * @param clazz Type to avoid casting * @return null. */ public static T notNull(Class clazz) { return (T) reportMatcher(NotNull.NOT_NULL).returnNull(); } /** * Not null argument. *

* alias to {@link Matchers#notNull()} *

* See examples in javadoc for {@link Matchers} class * * @return null. */ public static Object isNotNull() { return notNull(); } /** * Not null argument, not necessary of the given class. * The class argument is provided to avoid casting. *

* alias to {@link Matchers#notNull(Class)} *

* See examples in javadoc for {@link Matchers} class * * @param clazz Type to avoid casting * @return null. */ public static T isNotNull(Class clazz) { return notNull(clazz); } /** * String argument that contains the given substring. *

* See examples in javadoc for {@link Matchers} class * * @param substring * the substring. * @return empty String (""). */ public static String contains(String substring) { return reportMatcher(new Contains(substring)).returnString(); } /** * String argument that matches the given regular expression. *

* See examples in javadoc for {@link Matchers} class * * @param regex * the regular expression. * @return empty String (""). */ public static String matches(String regex) { return reportMatcher(new Matches(regex)).returnString(); } /** * String argument that ends with the given suffix. *

* See examples in javadoc for {@link Matchers} class * * @param suffix * the suffix. * @return empty String (""). */ public static String endsWith(String suffix) { return reportMatcher(new EndsWith(suffix)).returnString(); } /** * String argument that starts with the given prefix. *

* See examples in javadoc for {@link Matchers} class * * @param prefix * the prefix. * @return empty String (""). */ public static String startsWith(String prefix) { return reportMatcher(new StartsWith(prefix)).returnString(); } /** * Allows creating custom argument matchers. * This API has changed in 2.0, please read {@link ArgumentMatcher} for rationale and migration guide. * NullPointerException auto-unboxing caveat is described below. *

* It is important to understand the use cases and available options for dealing with non-trivial arguments * before implementing custom argument matchers. This way, you can select the best possible approach * for given scenario and produce highest quality test (clean and maintainable). * Please read the documentation for {@link ArgumentMatcher} to learn about approaches and see the examples. *

* NullPointerException auto-unboxing caveat. * In rare cases when matching primitive parameter types you *must* use relevant intThat(), floatThat(), etc. method. * This way you will avoid NullPointerException during auto-unboxing. * Due to how java works we don't really have a clean way of detecting this scenario and protecting the user from this problem. * Hopefully, the javadoc describes the problem and solution well. * If you have an idea how to fix the problem, let us know via the mailing list or the issue tracker. *

* See examples in javadoc for {@link ArgumentMatcher} class * * @param matcher decides whether argument matches * @return null. */ public static T argThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnNull(); } /** * Allows creating custom char argument matchers. * Note that {@link #argThat} will not work with primitive char matchers due to NullPointerException auto-unboxing caveat. *

* See examples in javadoc for {@link Matchers} class * * @param matcher decides whether argument matches * @return 0. */ public static char charThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnChar(); } /** * Allows creating custom boolean argument matchers. * Note that {@link #argThat} will not work with primitive boolean matchers due to NullPointerException auto-unboxing caveat. *

* See examples in javadoc for {@link Matchers} class * * @param matcher decides whether argument matches * @return false. */ public static boolean booleanThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnFalse(); } /** * Allows creating custom byte argument matchers. * Note that {@link #argThat} will not work with primitive byte matchers due to NullPointerException auto-unboxing caveat. *

* See examples in javadoc for {@link Matchers} class * * @param matcher decides whether argument matches * @return 0. */ public static byte byteThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnZero(); } /** * Allows creating custom short argument matchers. * Note that {@link #argThat} will not work with primitive short matchers due to NullPointerException auto-unboxing caveat. *

* See examples in javadoc for {@link Matchers} class * * @param matcher decides whether argument matches * @return 0. */ public static short shortThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnZero(); } /** * Allows creating custom int argument matchers. * Note that {@link #argThat} will not work with primitive int matchers due to NullPointerException auto-unboxing caveat. *

* See examples in javadoc for {@link Matchers} class * * @param matcher decides whether argument matches * @return 0. */ public static int intThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnZero(); } /** * Allows creating custom long argument matchers. * Note that {@link #argThat} will not work with primitive long matchers due to NullPointerException auto-unboxing caveat. *

* See examples in javadoc for {@link Matchers} class * * @param matcher decides whether argument matches * @return 0. */ public static long longThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnZero(); } /** * Allows creating custom float argument matchers. * Note that {@link #argThat} will not work with primitive float matchers due to NullPointerException auto-unboxing caveat. *

* See examples in javadoc for {@link Matchers} class * * @param matcher decides whether argument matches * @return 0. */ public static float floatThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnZero(); } /** * Allows creating custom double argument matchers. * Note that {@link #argThat} will not work with primitive double matchers due to NullPointerException auto-unboxing caveat. *

* See examples in javadoc for {@link Matchers} class * * @param matcher decides whether argument matches * @return 0. */ public static double doubleThat(ArgumentMatcher matcher) { return reportMatcher(matcher).returnZero(); } private static HandyReturnValues reportMatcher(ArgumentMatcher matcher) { return MOCKING_PROGRESS.getArgumentMatcherStorage().reportMatcher(matcher); } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy