JAVA @mock一个对象_java-jmock,每次调用都返回新对象

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值