Tuesday, 20 October 2009

Mocking a Get/Set Pair using EasyMock

Once again I'm going to tart up a post of SO and throw it on here:

Say you have an interface with a get/set pair that get populated and retrieved. And you need these to match.

public interface GetSetId {
    public int getID();
    public void setID(int id);
    public void somethingThatMakesThisNotAValueObject();
}

When it comes to testing items that depend on this you need to either - be able to know the get/set values in advance or write a little wrapper to remember the get/sets. In order to simplify this I humbly present:

public class GetSetAnswers<T> {
    private T value;
    public IAnswer<Object> set() {
        return new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                Object[] arguments = getCurrentArguments();
                value = (T) arguments[0];
                return null;
            }
        };
    }
   
    public IAnswer<T> get() {
        return new IAnswer<T>() {
            @Override
            public T answer() throws Throwable {
                return value;
            }
        };
    }
}

You can then use it thusly:
public class TestGetSet {
    @Test
    public void testSetGet() {
        GetSetAnswers<Integer> value = new GetSetAnswers<Integer>();
       
        GetSetId id = createMock(GetSetId.class);
        id.setID(anyInt());
        expectLastCall().andAnswer(value.set());
        expect(id.getID()).andAnswer(value.get());

        replay(id);
        int generatedValue = (int) (Math.random() * 100.0);
        id.setID(generatedValue);
        Assert.assertEquals(generatedValue, id.getID());
        verify(id);
    }
}

0 comments: