java – EasyMock并修改了一个可变的方法参数
发布时间:2020-12-14 05:51:14 所属栏目:Java 来源:网络整理
导读:如何使用EasyMock修改模拟方法的可变方法参数? 例如,我有一个使用BlockingQueue的类.我想模仿BlockingQueue成员进行单元测试.我的类调用方法queue.drainTo(Collection c).调用此方法将从队列中删除元素并将其添加到集合中.我如何使用EasyMock模拟这种行为?
如何使用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,并找到一种方法,在您希望从队列中删除数据的方法之前将所需的值插入队列. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |