java Mockito - 返回与传入方法相同的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26161917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito - returning the same object as passed into method
提问by LechP
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);
}
I'd like to test the behaviour of this method and thus want to mock the repository.merge
in following manner:
我想测试此方法的行为,因此想以repository.merge
以下方式模拟:
when(repository.merge(any(SomeEntity.class))).thenReturn(objectPassedAsArgument);
Then mocked repository returns that what makesSthWithEntity
passed to it and I can easily test it.
然后模拟存储库返回makesSthWithEntity
传递给它的内容,我可以轻松测试它。
Any ideas how can I force mockito to return objectPassedAsArgument
?
任何想法如何强制 mockito 返回objectPassedAsArgument
?
采纳答案by Mark Peters
You can implement an Answer
and then use thenAnswer()
instead.
您可以实现一个Answer
然后使用thenAnswer()
。
Something similar to:
类似于:
when(mock.someMethod(anyString())).thenAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
return invocation.getArguments()[0];
}
});
Of course, once you have this you can refactor the answer into a reusable answer called ReturnFirstArgument
or similar.
当然,一旦你有了这个,你就可以将答案重构为一个可重用的答案,称为ReturnFirstArgument
或类似的。
回答by Brice
Or better using mockito shipped answers
或者更好地使用 mockito 提供的答案
when(mock.something()).then(AdditionalAnswers.returnsFirstArg())
Where AdditionalAnswers.returnsFirstArg()
could be statically imported.
哪里AdditionalAnswers.returnsFirstArg()
可以静态导入。
回答by Filomat
It can be done easy with Java 8 lambdas:
使用 Java 8 lambdas 可以轻松完成:
when(mock.something(anyString())).thenAnswer(i -> i.getArguments()[0]);