4

Is it possible in Mockito to return the object that mocked method was called with? Without prior knowing what object it will be.

@Mock
MyObjectRepository myObjectRepository;
...
when(myObjectRepository.save(any(MyObject.class))) //save method returns normally MyObject.class object
     .thenReturn(\\the object that method was called with);

I want to return the object that is passed to save method.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
makozaki
  • 3,772
  • 4
  • 23
  • 47

1 Answers1

4

The following should work:

when(myObjectRepository.save(any(MyObject.class)))
     .then(AdditionalAnswers.returnsFirstArg());
João Dias
  • 16,277
  • 6
  • 33
  • 45
  • I tried it first with `.thenReturn(...)` and it failed, works perfectly with simply `.then(AdditionalAnswers.returnsFirstArg())` [link](https://www.baeldung.com/mockito-additionalanswers#1-returning-the-first-argument) – makozaki Dec 16 '21 at 13:10