views:

330

answers:

2

Hi, I have a method public Object doSomething(Object o); which I want to mock. It shall just return its parameter. I tried:

Capture<Object> copyCaptcher = new Capture<Object>(); expect(mock.doSomething(capture(copyCaptcher))).andReturn(copyCatcher.getValue()); wihtout success, I get just an AssertionError "Nothing captured, yet". Any ideas?

+1  A: 

Um, if I understand your question correctly I think you may be over complicating it.

Object someObject = .... ;
expect(mock.doSomething(someObject)).andReturn(someObject);

Should work just fine. Remember you are supplying both the expected parameter and returne value. So using the same object in both works.

Derek Clarkson
I don't know "someObject". It is instantiated in the method I want to test. Think of a method "createImage(InputStream image)" (cut) which internally calls a "Image filter(Image imge)" (mock).
Jan
Ahhh. ok. Then you can do a couple of things. Firstly you can test that the object is a particular class using the isA() argument matcher. Second I would suggest writing your own argument capture. I haven't done that, but I have written my own argument matchers. Which is really useful if you, for example, want to check bean properties. Unfortunately I don't have that code anymore, but if you look at the example of writing a matcher, it's not hard.
Derek Clarkson
+2  A: 

I was looking for the same behavior, and finally wrote the following :

import org.easymock.EasyMock;
import org.easymock.IAnswer;

/**
 * Enable a Captured argument to be answered to an Expectation.
 * For example, the Factory interface defines the following
 * <pre>
 *  CharSequence encode(final CharSequence data);
 * </pre>
 * For test purpose, we don't need to implement this method, thus it should be mocked.
 * <pre>
 * final Factory factory = mocks.createMock("factory", Factory.class);
 * final ArgumentAnswer<CharSequence> parrot = new ArgumentAnswer<CharSequence>();
 * EasyMock.expect(factory.encode(EasyMock.capture(new Capture<CharSequence>()))).andAnswer(parrot).anyTimes();
 * </pre>
 * Created on 22 juin 2010.
 * @author Remi Fouilloux
 *
 */
public class ArgumentAnswer implements IAnswer {

    private final int argumentOffset;

    public ArgumentAnswer() {
        this(0);
    }

    public ArgumentAnswer(int offset) {
        this.argumentOffset = offset;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public T answer() throws Throwable {
        final Object[] args = EasyMock.getCurrentArguments();
        if (args.length < (argumentOffset + 1)) {
            throw new IllegalArgumentException("There is no argument at offset " + argumentOffset);
        }
        return (T) args[argumentOffset];
    }

}

I wrote a quick "how to" in the javadoc of the class.

Hope this helps.

Remi Fouilloux
thanks! Although I changed the original unit test I'm sure I'll run into this issue again! (You maybe want to contribute it to EM direclty?)
Jan