0

I am using junit to run a few unit tests. One of these calls a method in an object that I mock using mockito like;

@Mock
private MyClass myClass;

I then set up mockito to do something like

Mockito.when(myClass.foo(Mockito.any()).thenReturn(bar);

Now myClass.foo actually takes another one of my classes (say class Person) as an argument and what I would like to do is something like this

Mockito.when(myClass.foo(Person parson)).thenDo(person.setName("Name")).thenReturn(bar);

That is of course pseudo code but I hope it illustrates what I am trying to do. Is this possible?

Lieuwe
  • 1,734
  • 2
  • 27
  • 41

2 Answers2

0

You need to use thenAnswer or its twin doAnswer method.

See Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

If your answers become too complicated, consider using a fake instead of a mock.

Lesiak
  • 22,088
  • 2
  • 41
  • 65
0

In this case if your goal is to set field of Person object you can do that before or after the line:

Mockito.when(myClass.foo(Mockito.any()).thenReturn(bar);

doAnswer() would help do operations based on input, but operations would be performed on copy of arguments not the original arguments.

tejas.bargal
  • 111
  • 5