EasyMock Argument Matchers With Example

EasyMock argument matchers allow us to provide the flexible argument for matching when stubbing the methods. You will find a lot of any*() methods in EasyMock that can be used with expect() to provide arguments for a method call.

EasyMock Argument Matchers Example

Let’s look at a simple example of mocking ArrayList and stubbing its behaviors for any argument of a specific type.

Notice the use of anyInt() and anyString() for specifying the argument as any int or string object.

Apart from matching any argument, there are some other argument matchers too. Let’s look at some of these argument matchers with example code.

Equality Argument Matcher

We can use same() argument matcher method for stubbing behavior with same object. If you want to perform equality check, use eq() method.

Comparison Argument Matcher

We can use lt(), gt(), leq() and geq() methods to compare arguments and return specific output. Note that these methods are overloaded to use with primitive data types as well as objects. If you are using them with any Object, then they should be Comparable.

Conditional Argument Matchers

We can use and(), or() and not() functions with argument matchers to write more complex behaviors.

Note that when we are using argument matchers to stub behaviors, every argument has to be a matcher otherwise, we will get an error message. So if we have to specify not(100), then write it as not(eq(100)).

Here is a simple example of using conditional argument matchers.

Null Argument Matchers

We can use isNull() and notNull() to match null and not-null arguments. However, isNull() comes handy when we are using other argument matchers and can’t use null directly.

String Argument Matchers

There are few utility methods especially for matching String arguments. These are:

  • startsWith(String)
  • endsWith(String)
  • contains(String)
  • matches(Regex): Expects argument string to match the regex.
  • find(Regex): Expects one of the substring to match the regex.

Here is a simple example showing usage of string argument matchers.

Custom Argument Matcher

Although EasyMock argument matchers support is extensive, if you want to implement a custom argument matcher then you can implement IArgumentMatcher interface and use it through EasyMock.reportMatcher(IArgumentMatcher).

You can checkout complete project and more EasyMock examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: