jmock,每次调用时返回新对象

时间:2012-08-22 12:52:25

标签: java jmock

我正在设置一个模拟对象,每当我调用一个方法f()时,它就会返回一个新的业务对象。如果我简单地说returnValue(new BusinessObj()),它将在每次调用时返回相同的引用。如果我不知道有多少次调用f(),即我不能使用onConsecutiveCalls,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

您需要声明CustomAction实例来代替标准returnValue子句:

allowing(mockedObject).f();
will(new CustomAction("Returns new BusinessObj instance") {
  @Override
  public Object invoke(Invocation invocation) throws Throwable {
    return new BusinessObj();
  }
});

以下是一个独立的单元测试,用于演示:

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.action.CustomAction;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMock.class)
public class TestClass {

  Mockery context = new JUnit4Mockery();

  @Test
  public void testMethod() {
    final Foo foo = context.mock(Foo.class);

    context.checking(new Expectations() {
      {
        allowing(foo).f();
        will(new CustomAction("Returns new BusinessObj instance") {
          @Override
          public Object invoke(Invocation invocation) throws Throwable {
            return new BusinessObj();
          }
        });
      }
    });

    BusinessObj obj1 = foo.f();
    BusinessObj obj2 = foo.f();

    Assert.assertNotNull(obj1);
    Assert.assertNotNull(obj2);
    Assert.assertNotSame(obj1, obj2);
  }

  private interface Foo {
    BusinessObj f();
  }

  private static class BusinessObj {
  }
}