21.2.12

EasyMock: Verify Arguments

Sometimes, when you are using EasyMock you do not just want to verify the behavior of some class, but also the state of some created objects you actually have no access to. E.g. you are testing a method that builds an object and passes this to your created mock.
EasyMock provides the following possiblity to gain access to these arguments:

    @Test
    public void checkThePassedObject(){
        SomeEJB someEjb = createMock(SomeEJB.class);
        someEjb.timeSomething(anyObject(Timer.class));
        expectLastCall().andAnswer(new IAnswer<Object>() {
            public Object answer() throws Throwable {
                passedTimer = (Timer) getCurrentArguments()[0];
                return null;
            }
        });
       
        replay(someEjb);
        classUT.setSomeEjb(someEjb);
        classUT.createSpecialTimer();
        Assert.assertNotNull(passedTimer);
        verify(someEjb);
    }

The actual magic happens in the anonymous IAnswer class; within the implemented answer method you can do whatever you want. In this case we simply retrieve the passed objects using the getCurrentArguments method. And thats it. Simple as that.

However, if you do not care about your mock behavior at all, how often it is called, what parameters are passed or if it is even called, you can use the andStubReturn method:

SomeEJB someEjb = createMock(SomeEJB.class);
expect(someEjb.removeDigits(not(eq("")))).andStubReturn("no_digits");

In this case, whenever the method is called with a not empty string the mock will return "no_digits".

No comments:

Post a Comment