I have to mock a method using jmockit which returns the same arguments I passed. With Mockito, I used AdditionalAnswers.returnsFirstArg:
PowerMockito.when(entityManager.merge((Request)Mockito.any())).then(AdditionalAnswers.returnsFirstArg());
How can I write this with jmockit?
new Expectations() {
{
entityManager.merge((Request) any);
returns(????);
}
};
JMockit doesn't have this feature out-of-the-box, but it can be implemented easily enough, with a reusable Delegate
class:
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);
}