EasyMock和修改可变方法参数 [英] EasyMock and modifing a mutable method parameter

查看:410
本文介绍了EasyMock和修改可变方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用EasyMock修改模拟方法的可变方法参数?

How does one use EasyMock to modify a mocked method's mutable method parameter?

例如,我有一个使用BlockingQueue的类.我想模拟BlockingQueue成员进行单元测试.我的班级叫方法queue.drainTo(Collection c).调用此方法将从队列中删除元素,并将其添加到集合中.我如何使用EasyMock模拟这种行为?例子会很棒.

For example, I have class that uses a BlockingQueue. I want to mock the BlockingQueue member for unit testing. My class calls the method queue.drainTo(Collection c). Calling this method removes elements from the queue and adds them to the collection. How would I mock this behavior using EasyMock? Examples would be great.

推荐答案

您可以使用有时它有助于提取帮助程序类或方法:

It sometimes helps to extract a helper class or method:

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();
    }
  };
}

然后您可以执行以下操作:

Then you can do:

List<Foo> drainedElements = Arrays.asList(new Foo(123), new Foo(42));
EasyMock.expect(queue.drainTo(EasyMock.isA(List.class)))
    .andAnswer(fakeDrainReturning(drainedElements));

最好使用实数BlockingQueue并找到一种在期望从队列中删除数据的方法之前将所需值插入队列的方法.

It might be better to use a real BlockingQueue and find a way to insert the desired value into the queue before the method that you expect to remove data from the queue.

这篇关于EasyMock和修改可变方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆