Mockito returnFirstArg()使用 [英] Mockito returnsFirstArg() to use
本文介绍了Mockito returnFirstArg()使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经开始使用Mockito AdditionalAnswers#returnsFirstArg
,这很棒:
I've started using the Mockito AdditionalAnswers#returnsFirstArg
, which is great:
when(myMock.myFunction(anyString())).then(returnsFirstArg());
但我想知道是否有一种简单的方法来提取输入参数以便用于类似于以下构造函数的示例:
but I was wondering if there is an easy way to extract the input argument in order to be used for example in a constructor like:
when(myMock.myFunction(anyString())).thenReturn(new MyObject((String)returnsFirstArg()));
(显然不起作用......)
(which obviously doesn't work...)
推荐答案
最简单的(只有?)方法,恕我直言,将使用 thenAnswer
方法,它允许你不仅返回一个值,而且实际执行一些代码。 Java 8使这个特别优雅,因为你可以使用匿名lambda:
The easiest (only?) approach, IMHO, would be to use the thenAnswer
method, which allows you to not only return a value, but actually execute some code. Java 8 makes this particularly elegant, as you could just use an anonymous lambda:
when(myMock.myFunction(anyString()))
.thenAnswer(i -> new MyObject((String)i.getArguments()[0]);
这篇关于Mockito returnFirstArg()使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文