Published by Fabian on 06 Oct 2008
Writing a Custom Easymock Argument Matcher
Easymock is a great tool, but for me it was lacking a neat way to make sure that a recorded method call is only valid for an agument with a specific property value. Easymock has a mechanism that could be used for that:
public static <T> cmp(T value, Comparator<T> comparator, LogicalOperator operator)
However I do not find this very telling.
So I ended up writing a custom IArgumentMatcher:
private ObjectClass hasPropertyEnum(final MyPropertyEnum enumValue) { reportMatcher(new IArgumentMatcher() { @Override public void appendTo(StringBuffer buffer) { buffer.append("hasPropertyEnum("+enumValue+")"); } @Override public boolean matches(Object argument) { if (argument instanceof ObjectClass ) { ObjectClass clazz = (ObjectClass ) argument; if (enumValue!= null) { return enumValue.equals(clazz.getMyProperty()); } } return false; } }); return null; }
At least I find this much more telling than writing a comparator.
Now I am able to record a call like this:
expect(myServiceMock.myMethod(hasPropertyEnum(MyPropertyEnum.A_ENUM))).andReturn(null);
Or is there a nicer Easymock solution?