0

I have a recursive function under test f1. f1 calls a database service which I am mocking.

def f1 {
  result = databaseservicecall(arg); //mocking this
  add result to accumulator
  exit recursion if some condition is met else call f1 again.
}

I want that databaseserviecall returns say r1 on 1st call, r2 in the second call and the accumulator should have r1+r2. Alternatively, I am also Ok if I could test that databaseservicecall was called 2 times and that it was passed say arg1 and arg2 as arguments.

Is it possible to do this in mockito? I thought I can use a spy but I don't have a real implementation of databaseservicecall.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184

2 Answers2

0

Take advantage of the thenAnswer feature (doAnswer if you are working with a spy):

Integer invocationCount = Integer.valueOf(0);

when(sut.databaseservicecall(any(Argument.class))).thenAnswer((invocation) ->{
   invocationCount++;

   if(invocationCount == 1) return r1;
   if(invocationCount == 2) return r2;
   if(...)


   return null;
});

More on the feature.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
0

You can just concatenate then () calls.

when(sut.databaseservicecall(any()))
    .then(r1)
    .then(r2) ;
daniu
  • 14,137
  • 4
  • 32
  • 53