如何在easymock中模拟一个返回其中一个参数的方法? [英] How can I mock a method in easymock that shall return one of its parameters?
本文介绍了如何在easymock中模拟一个返回其中一个参数的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要模拟的public Object doSomething(Object o);
。它应该只返回它的参数。我试过了:
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());
但是没有成功,我只得到AssertionError为 java.lang.AssertionError :还没有捕获
。任何想法?
but without success, I get just an AssertionError as java.lang.AssertionError: Nothing captured yet
. Any ideas?
推荐答案
我一直在寻找相同的行为,最后写了以下内容:
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<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。
I wrote a quick "how to" in the javadoc of the class.
希望这会有所帮助。
这篇关于如何在easymock中模拟一个返回其中一个参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文