Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java jmock,在每次调用时返回新对象_Java_Jmock - Fatal编程技术网

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

Java jmock,在每次调用时返回新对象,java,jmock,Java,Jmock,我正在设置一个模拟对象,该对象应该在每次对其调用方法f()时返回一个新的业务对象。如果我简单地说returnValue(new BusinessObj()),它将在每次调用时返回相同的引用。如果我不知道将有多少调用f(),即我无法使用OnConcecutiveCalls,我如何解决此问题?您需要声明一个CustomAction实例来代替标准的returnValue子句: allowing(mockedObject).f(); will(new CustomAction("Returns new

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

您需要声明一个
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 {
  }
}