0

In following discussions were provided ways to stub method for several sequential calls:

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.

  • 1
    You could forward numb to the supplier, which then becomes a function. The real problem, however, might be that you want to make a concurrent - and thus inherently non-deterministic behaviour - deterministic in your tests. My suggestions is to split those aspects in different tests. How to do that depends on the real scenario and real test goal. Your example looks to „abstractified“ for a good suggestion. So what is it you want to test in the Runner object? – johanneslink Jan 08 '22 at 11:25

0 Answers0