Mockito returnsFirstArg() to use

Gep :

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...)

Mureinik :

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]);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459938&siteId=1