如何在easymock中模拟一个返回其中一个参数的方法?

Jan*_*Jan 30 java easymock mocking capture

public Object doSomething(Object o);我想嘲笑.它应该只返回它的参数.我试过了:

Capture<Object> copyCaptcher = new Capture<Object>();
expect(mock.doSomething(capture(copyCaptcher)))
        .andReturn(copyCatcher.getValue());
Run Code Online (Sandbox Code Playgroud)

但是没有成功,我只得到一个AssertionError java.lang.AssertionError: Nothing captured yet.有任何想法吗?

小智 26

嗯,最简单的方法是在IAnswer实现中使用Capture ...当你在内联时,你必须声明它final.

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)
Run Code Online (Sandbox Code Playgroud)

这可能是最精确的方式,而不依赖于某些上下文信息.这对我来说每次都有诀窍.

  • 很好的答案。使用 Java 8 lambda 的整个 IAnswer 匿名子类可以重写为“myCapture::getValue”。 (3认同)

小智 18

我一直在寻找相同的行为,最后写了以下内容:

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<T> implements IAnswer<T> {

    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];
    }

}

我在类的javadoc中写了一个快速的"how to".

希望这可以帮助.

  • Capture是你的javadoc示例中的红色鲱鱼 - 它不需要:EasyMock.expect(factory.encode(anyObject())).andAnswer(parrot).anyTimes(); (3认同)

the*_*man 16

捕获用于测试之后传递给模拟的值.如果您只需要一个模拟来返回一个参数(或从参数计算出的某个值),您只需要实现IAnswer.

如果你想要一个可重用的方法来传递参数X,请参阅"Remi Fouilloux"的实现,但忽略他在示例中使用Capture.

如果你只是想像"do_the_trick"的例子那样内联它,那么Capture就是一个红色的鲱鱼.这是简化版本:

MyService mock = createMock(MyService.class);
expect(mock.someMethod(anyObject(), anyObject()).andAnswer(
    new IAnswer<ReturnType>() {
        @Override
        public ReturnType answer() throws Throwable {
            // you could do work here to return something different if you needed.
            return (ReturnType) EasyMock.getCurrentArguments()[0]; 
        }
    }
);
replay(mock)
Run Code Online (Sandbox Code Playgroud)


小智 9

基于@does_the_trick并使用lambdas,您现在可以编写以下内容:

MyService mock = EasyMock.createMock(MyService.class);

final Capture<ParamAndReturnType> myCapture = EasyMock.newCapture();
expect(mock.someMethod(capture(myCapture))).andAnswer(() -> myCapture.getValue());
Run Code Online (Sandbox Code Playgroud)

或@thetoolman建议没有捕获

expect(mock.someMethod(capture(myCapture)))
.andAnswer(() -> (ParamAndReturnType)EasyMock.getCurrentArguments()[0]);
Run Code Online (Sandbox Code Playgroud)