我必须使用jmockit模拟一个方法,该方法返回与我传递的参数相同的参数。对于Mockito,我使用了AdditionalAnswers.returnsFirstArg:
PowerMockito.when(entityManager.merge((Request)Mockito.any())).then(AdditionalAnswers.returnsFirstArg());
我如何用jmockit写这个?
new Expectations() {
{
entityManager.merge((Request) any);
returns(????);
}
};
JMockit没有现成的功能,但它可以很容易地实现,有一个可重用的Delegate
类:
class FirstArgument implements Delegate<Object> {
Object delegate(Invocation inv) { return inv.getInvokedArguments()[0]; }
}
@Mocked EntityManager entityManager;
@Test
public void expectationRecordedToReturnAnArgument()
{
new Expectations() {{
entityManager.merge(any);
result = new FirstArgument();
}};
// From the code under test:
EntityClass entity = new EntityClass();
EntityClass merged = entityManager.merge(entity);
assertSame(entity, merged);
}