In following discussions were provided ways to stub method for several sequential calls:
- How to change return value of mocked method with no argument on each invocation?
- Using Mockito with multiple calls to the same method with the same arguments
Is there any way to stub method without arguments, which is called several times in random order, but with ability to distinguish calls from each other, for example by invocation context?
Code example:
class Supplier {
public String get() {
return "";
}
}
class Runner {
public Supplier supplier;
public CompletableFuture<String> runAsync(int numb) {
return CompletableFuture.supplyAsync(() -> supplier.get());
}
}
@ExtendWith(MockitoExtension.class)
class Tests {
@Mock
Supplier supplierMock;
@InjectMocks
Runner runner;
@Test
void test() throws ExecutionException, InterruptedException {
Mockito.when(supplierMock.get()).thenReturn("1", "2", "3");
CompletableFuture<String> future1 = runner.runAsync(1);
CompletableFuture<String> future2 = runner.runAsync(2);
CompletableFuture<String> future3 = runner.runAsync(3);
System.out.println(future1.get());
System.out.println(future2.get());
System.out.println(future3.get());
}
}
In this example digits 1, 2 and 3 are printed in random order because of parallel procesing. What i want is to bind each stub to certain call. It means i want to get result related to first thenReturn argument in future1, result related to second argument in future2, etc. For example, using arguments of runAsync (numb in example) somehow. Is there way to achieve this?
ps. In my real case return value is not String but another mock, different for each call. And these mocks expected to have different behaviour.