How can I mock a method in easymock that shall return one of its parameters?

Jan picture Jan · Apr 19, 2010 · Viewed 40.1k times · Source

public Object doSomething(Object o); which I want to mock. It should just return its parameter. I tried:

Capture<Object> copyCaptcher = new Capture<Object>();
expect(mock.doSomething(capture(copyCaptcher)))
        .andReturn(copyCatcher.getValue());

but without success, I get just an AssertionError as java.lang.AssertionError: Nothing captured yet. Any ideas?

Answer

does_the_trick picture does_the_trick · Oct 17, 2011

Well, the easiest way would be to just use the Capture in the IAnswer implementation... when doing this inline you have to declare it final of course.

MyService mock = createMock(MyService.class);

final Capture<ParamAndReturnType> myCapture = new Capture<ParamAndReturnType>();
expect(mock.someMethod(capture(myCapture))).andAnswer(
    new IAnswer<ParamAndReturnType>() {
        @Override
        public ParamAndReturnType answer() throws Throwable {
            return myCapture.getValue();
        }
    }
);
replay(mock)

This is probably the most exact way, without relying on some context information. This does the trick for me every time.