EasyMock: Get real parameter value for EasyMock.anyObject()?

Armen picture Armen · Jan 8, 2014 · Viewed 19.1k times · Source

In my unit tests I'm using EasyMock for creating mock objects. In my test code I have something like this

EasyMock.expect(mockObject.someMethod(anyObject())).andReturn(1.5);

So, now EasyMock will accept any call to someMethod(). Is there any way to get real value that is passed to mockObject.someMethod(), or I need to write EasyMock.expect() statement for all possible cases?

Answer

hoaz picture hoaz · Jan 8, 2014

You can use Capture class to expect and capture parameter value:

Capture capturedArgument = new Capture();
EasyMock.expect(mockObject.someMethod(EasyMock.capture(capturedArgument)).andReturn(1.5);

Assert.assertEquals(expectedValue, capturedArgument.getValue());

Note that Capture is generic type and you can parametrize it with an argument class:

Capture<Integer> integerArgument = new Capture<Integer>();

Update:

If you want to return different values for different arguments in your expect definition, you can use andAnswer method:

EasyMock.expect(mockObject.someMethod(EasyMock.capture(integerArgument)).andAnswer(
    new IAnswer<Integer>() {
        @Override
        public Integer answer() {
            return integerArgument.getValue(); // captured value if available at this point
        }
    }
);

As pointed in comments, another option is to use getCurrentArguments() call inside answer:

EasyMock.expect(mockObject.someMethod(anyObject()).andAnswer(
    new IAnswer<Integer>() {
        @Override
        public Integer answer() {
            return (Integer) EasyMock.getCurrentArguments()[0];
        }
    }
);