Mockito + PowerMock : Using ArgumentMatchers

HarshaVardhanReddy Bommareddy
2 min readDec 10, 2019

--

Hello Everyone!

For “Developers” it’s mandate to have unit test cases for each line of the code to make it better. In fact following TDD(Test Driven Development) would be great.

Anyways that’s not gonna be our topic.

The goal of this article is to provide understanding on ArgumentMatchers for those who use Mockito and PowerMock.

Matchers was the child class of ArgumentMatchers and now it is deprecated from the version 3.2.0 of mockito-core in order to avoid a name clash with Hamcrest org.hamcrest.Matchers class.

What is ArgumentMatchers for ?

ArgumentMatchers allows us to mock the method behavior for any argument.

Let’s look at few methods of the ArgumentMatchers.

  • any() → Matches anything (null values)
  • anyString() → Matches non-null Strings
  • anyBoolean() → Matches any boolean or non-null Boolean
  • anyInt() → Matches any int or non-null Integer
  • anyFloat() → Matches any float or non-null Float
  • anyLong() → Matches any long or non-null Long
  • anyList() → Matches any non-null List
  • anyMap() → Matches any non-null Map

These are few methods which are frequently used for matching the arguments of stubbed methods.

How to use ArgumentMatchers ?

The below snippets are examples for how to user ArgumentMatchers

//stubbing using anyInt()
Powemockito.when(mockObj.get(anyInt())).thenReturn(returnValue);
//stubbing using anyBoolean()
Powemockito.when(mockObj.run(anyBoolean())).thenReturn(returnValue);
//stubbing using anyString()
Powemockito.when(mockObj.run(anyString())).thenReturn(returnValue);

Yes, it looks simple and you are right. But, myself faced few hurdles. Some of them are:

  • Passing null as parameter
//stubbing using isNull()
Powemockito.when(mockObj.run(isNull())).thenReturn(returnValue);
mockObj.run(null);
  • Stubbing an overloaded method

This happens when you are using Singleton class to get instance for a Class and it might also extend a different class having the same method. This might happen rarely but it happens.

Powemockito.when(mockObj.run(any(Example.class))).thenReturn(returnValue);

Conclusion

  • Matchers class was used to stub methods for with arguments
  • Matchers is deprecated from mockito-core version 3.2.0 to avoid name clash with Hamcrest org.hamcrest.Matchers
  • ArgumentMatchers is parent class of Matchers, Mockito
  • Mockito extends ArgumentMatchers so to get access to all matchers just import Mockito class statically.

References

Help me grow by dropping suggestions. Thanks for reading and hope this article helps!

Happy Coding! Happy Testing!

--

--