0

suppose I want to mock a method with the following signature:

public A foo(A a)

I want foo to be mocked in a way that it returned what it received (that is the same instance a)

I tried unsuccessfully the following:

Capture<A> capture = new Capture();
expect(myclass.foo(capture)).andReturn(capture.getValue());

This does not work because the capture is still empty when getValue() is called.

Any ideas?

Thanks

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
odwl
  • 2,095
  • 2
  • 17
  • 15

1 Answers1

4
public class A {

    public <A> A foo(A a) {
        return null;
    }

    public static void main(String[] args) throws Exception {
        A mock = createNiceMock(A.class);

        expect(mock.foo(anyObject())).andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                return EasyMock.getCurrentArguments()[0];
            }
        }).anyTimes();

        replay(mock);

        System.out.println(mock.foo("1"));
        System.out.println(mock.foo(2L));
    }
}

Prints out:

1
2
dur
  • 15,689
  • 25
  • 79
  • 125
IAdapter
  • 62,595
  • 73
  • 179
  • 242
  • Looks a bit too complex. Is there not an easier way? – odwl Aug 18 '10 at 09:57
  • you could extract answer to your own class. – IAdapter Aug 18 '10 at 10:22
  • Example of extracting to separate class: http://stackoverflow.com/questions/2667172/how-can-i-mock-a-method-in-easymock-that-shall-return-one-of-its-parameters Define it once, then everywhere you want to use it you just say expect(...).andAnswer(new ArgumentAnswer()) – wrschneider Sep 28 '11 at 17:22
  • You can also use your capture within the IAnswer, to save some potential casting and editing argument position in two places. In that case, it should also be possible to create a generic AnswerWithCapture that works in all cases and takes a Capture instance as a constructor argument. – Anthop Jun 22 '19 at 12:07