Mockito:如何根据其参数之一模拟方法的结果?

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

有没有办法将参数传递给模拟函数并在其中使用该参数值。示例(通知名称作为参数):

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

有办法吗?

您需要使用 thenAnswer,并从 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")
);