如何使用EasyMock修改模拟方法的可变方法参数?
例如,我有一个使用BlockingQueue的类.我想模仿BlockingQueue成员进行单元测试.我的类调用方法queue.drainTo(Collection c).调用此方法将从队列中删除元素并将其添加到集合中.我如何使用EasyMock模拟这种行为?例子很棒.
解决方法
您可以使用
andAnswer和
getCurrentArguments:
public void testDrainToQueue() {
BlockingQueue<Foo> queue = EasyMock.createMock(BlockingQueue.class);
EasyMock.expect(queue.drainTo(EasyMock.isA(List.class)))
.andAnswer(new IAnswer<Integer>() {
public Integer answer() {
((List) EasyMock.getCurrentArguments()[0]).add(new Foo(123));
return 1; // 1 element drained
}
});
EasyMock.replay(queue);
...
}
有时候有助于提取辅助类或方法:
private static IAnswer<Integer> fakeDrainReturning(final List drainedElements) {
return new IAnswer<Integer() {
@Override public Integer answer() {
((List) EasyMock.getCurrentArguments()[0]).addAll(drainedElements);
return drainedElements.size();
}
};
}
然后你可以这样做:
List<Foo> drainedElements = Arrays.asList(new Foo(123),new Foo(42));
EasyMock.expect(queue.drainTo(EasyMock.isA(List.class)))
.andAnswer(fakeDrainReturning(drainedElements));
最好使用真正的BlockingQueue,并找到一种方法,在您希望从队列中删除数据的方法之前将所需的值插入队列.