Monday, February 22, 2010

Relection equals Matcher - Easy Mock made even easier

Easymock is great tool to produce mock object and do true unit testing verifying the expected behavior of your class.

One issue faced times to times is  while verifying the behavior it uses equals to verify objects passed as arguments are same.

It should work great in most of the cases, but living in the real world most of the times equals is not defined.
Of course you should define a true equals function, but sometimes you can't even do it, since you might not be able to modify the parameter.
Arguably you want to test the behavior of your class, no modifying the argument itself.

So here is a simple Matcher using Apache commons EqualsBuilder:
public  class ReflectionEqualsMatcher<t> implements IArgumentMatcher
{
    private T expected;

    public ReflectionEqualsMatcher(T expected)
    {
        this.expected = expected;
    }

    public static <S> S eqReflect(S toCompare)
    {
        EasyMock.reportMatcher(new ReflectionEqualsMatcher<S>(toCompare));
        return toCompare;
    }


    public boolean matches(Object o)
    {
        return EqualsBuilder.reflectionEquals(expected, o);
    }

    public void appendTo(StringBuffer buffer) {
        buffer.append("eqReflect(");
        buffer.append(expected.toString());
        buffer.append(")");

    }

No comments: