Search code examples
javaspringmockitojooq

Mockito: how to mock method with the result depending on one of its parameters?


Is there a way to pass params to mocked function and use that param value inside. Example (notice name as param):

Mockito.when(clientRepo.registerNewClient(Mockito.any(String.class) as name))
    .thenReturn(
        dslContext
            .insertInto(CLIENT)
            .set(CLIENT.CLIENT_NAME, name)
            .execute());

Is there a way to do that?


Solution

  • You need to use thenAnswer, and get your argument from the InvocationOnMock.

    final Repo clientRepo = Mockito.mock(Repo.class);
    Mockito.when(clientRepo.registerNewClient(Mockito.any(String.class)))
        .thenAnswer(
            (Answer<Client>)
                invocationOnMock -> new Client(
                    invocationOnMock
                        .getArgumentAt(0, String.class)
                        .toUpperCase()
                )
        );
    Assertions.assertEquals(
        clientRepo.registerNewClient("fff"), new Client("FFF")
    );