15

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?

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
Armen
  • 255
  • 1
  • 2
  • 12

1 Answers1

29

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];
        }
    }
);
hoaz
  • 9,883
  • 4
  • 42
  • 53
  • Thanks for answer. But it is not possible to call capturedArgument.getValue() in andReturn method right? andReturn(capturedArgument.getValue()) – Armen Jan 08 '14 at 21:29
  • I found it, when I use andAnswer insted of andReturn it is possible to use capturedArgument.getValue() for return value, **Thanks for help*** – Armen Jan 08 '14 at 21:43
  • 3
    inside an andAnswer() you can also call the method getCurrentArguments() which returns an Object[] of all the parameters passed in – dkatzel Jan 08 '14 at 22:00
  • You can also capture elements with a void method through `myObject.myMethod(capture(captureElement));` then `expectLastCall()` – herau Aug 14 '14 at 10:23
  • Calling the `Capture`class constructor is deprecated. Call `EasyMock.newCapture()` instead. – Stephan Nov 12 '17 at 10:10