简体   繁体   English

Mockito:给定Class的实例返回相同的实例

[英]Mockito : given an instance of Class return the same instance

I m trying to use mockito to mock a service. 我正在尝试使用Mockito模拟服务。 However I m not finding a way to say to mockito that given an instance of a class return me the same instance : 但是我没有找到一种方法来对嘲笑说给定一个类的实例返回相同的实例:

Something like : 就像是 :

  given(service.add(any(Individual.class)).willReturn(any(Individual.class));

any Idea how may I do that ? 任何想法我该怎么做?

You can analyze invocation to access argument. 您可以分析调用以访问参数。

    given(service.add(any(Individual.class)))
            .will(invocation -> invocation.getArgument(0));

You could use AdditionalAnswers.returnsFirstArg() : 您可以使用AdditionalAnswers.returnsFirstArg()

when(service.add(any(Individual.class)).then(AdditionalAnswers.returnsFirstArg());

or with the BDD wrapper : 或使用BDD包装器:

given(service.add(any(Individual.class)).willReturn(AdditionalAnswers.returnsFirstArg());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM