org.mockito
Class ArgumentMatcher<T>

java.lang.Object
  extended by org.hamcrest.BaseMatcher<T>
      extended by org.mockito.ArgumentMatcher<T>
Type Parameters:
T - type of argument
All Implemented Interfaces:
org.hamcrest.Matcher<T>, org.hamcrest.SelfDescribing
Direct Known Subclasses:
And, Any, Compare, CompareTo, Contains, EndsWith, Equals, EqualsWithDelta, Find, InstanceOf, Matches, Not, NotNull, Null, Or, ReflectionEquals, Same, StartsWith

public abstract class ArgumentMatcher<T>
extends org.hamcrest.BaseMatcher<T>

Allows creating customized argument matchers.

ArgumentMatcher is an hamcrest Matcher with predefined describeTo() method. In case of failure, ArgumentMatcher generates description based on decamelized class name - to promote meaningful class names. For example StringWithStrongLanguage matcher will generate 'String with strong language' description. You can always override describeTo() method and provide detailed description.

Use Matchers.argThat(org.hamcrest.Matcher) method and pass an instance of hamcrest Matcher, e.g:

 class IsListOfTwoElements extends ArgumentMatcher {
     public boolean matches(Object list) {
         return ((List) list).size() == 2;
     }
 }
 
 List mock = mock(List.class);
 
 stub(mock.addAll(argThat(new IsListOfTwoElements()))).toReturn(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());
 
Custom argument matchers 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.

Read more about Matchers


Constructor Summary
ArgumentMatcher()
           
 
Method Summary
 void describeTo(org.hamcrest.Description description)
           
abstract  boolean matches(java.lang.Object argument)
          Returns whether this matcher accepts the given argument.
 
Methods inherited from class org.hamcrest.BaseMatcher
_dont_implement_Matcher___instead_extend_BaseMatcher_, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ArgumentMatcher

public ArgumentMatcher()
Method Detail

matches

public abstract boolean matches(java.lang.Object argument)
Returns whether this matcher accepts the given argument.

The method should never assert if the argument doesn't match. It should only return false.

Parameters:
argument - the argument
Returns:
whether this matcher accepts the given argument.

describeTo

public void describeTo(org.hamcrest.Description description)