A better eq() when matching method arguments with Mockito

I learned late of Mockito [1], even so more I love it. Walking a little farther away from the basics, a frequent needs presents itself to match method parameters (either when specifying or verifying behaviour) based on properties of complex objects which do not implement the java equals contract.

Such an example would be verifying that an order is passed to a checkout method which contains a certain confirmation email address:

verify(orderService).dispatchOrder(withEmail(order,"test@example.com"));

Hamcrest matchers and generics to our rescue:

static  T withEmail(final T model, final String email){

BaseMatcher m = new BaseMatcher() {

@Override
public boolean matches(Object o) {
if (!(o instanceof HasEmail))
return false;
return ((HasEmail)o).getEmail().equals(email);
}

@Override
public void describeTo(Description arg) {
}
};

return Mockito.argThat(m);
}

Resources

[1] Mockito testing library
http://code.google.com/p/mockito/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s