Java – easymock and modified a variable method parameter

How to use easymock to modify the variable method parameters of simulation methods?

For example, I have a class that uses BlockingQueue I want to imitate BlockingQueue members for unit testing My class calls the method queue drainTo(Collection c). Calling this method removes the element from the queue and adds it to the collection How can I use easymock to simulate this behavior? Great example

Solution

You can use andanswer and 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);
  ...
}

Sometimes it helps to extract helper classes or methods:

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 this:

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

It's best to use a real BlockingQueue and find a way to insert the required values into the queue before you want to delete the data from the queue

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>