gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:21:17 26 4
gpt4 key购买 nike

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

最佳答案

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

关于java - jmock,每次调用时返回新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12073594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com