问题描述
假设我在某个服务类中有以下方法:
Let's imagine I have a following method in some service class:
public SomeEntity makeSthWithEntity(someArgs){
SomeEntity entity = new SomeEntity();
/**
* here goes some logic concerning the entity
*/
return repository.merge(entity);
}
我想测试此方法的行为,因此想以下列方式模拟 repository.merge
:
I'd like to test the behaviour of this method and thus want to mock the repository.merge
in following manner:
when(repository.merge(any(SomeEntity.class))).thenReturn(objectPassedAsArgument);
然后模拟存储库返回 makesSthWithEntity
传递给它的内容,我可以轻松地对其进行测试.
Then mocked repository returns that what makesSthWithEntity
passed to it and I can easily test it.
任何想法如何强制 mockito 返回 objectPassedAsArgument
?
Any ideas how can I force mockito to return objectPassedAsArgument
?
推荐答案
您可以实现一个 Answer
,然后使用 thenAnswer()
代替.
You can implement an Answer
and then use thenAnswer()
instead.
类似于:
when(mock.someMethod(anyString())).thenAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
return invocation.getArguments()[0];
}
});
当然,一旦你有了这个,你就可以将答案重构为一个可重用的答案,称为 ReturnFirstArgument
或类似的.
Of course, once you have this you can refactor the answer into a reusable answer called ReturnFirstArgument
or similar.
这篇关于Mockito - 返回与传入方法相同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!