6

I am testing one method. It requests the same function of a mocked object twice but with different parameters passed. Naturally, I need two different answers, but mockk gives me the same answer for both.

every { userRepository.getUser("A") }.answers { userA }
every { userRepository.getUser("B") }.answers { userB }

How can I get two different results using mockk?

rethab
  • 7,170
  • 29
  • 46

1 Answers1

7

As stated in the comment to the question, this can be achieved simply by specifying the parameters.

However, if the condition is more involved, the same thing can be achieved by capturing slots.

For example if we wanted to return 42 if the user's id was 1, and 35 otherwise:

val userSlot = slot<User>()
every { userRepository.saveUser(capture(userSlot)) } answers {
  if (userSlot.captured.id == 1) 42
  else 35
}
rethab
  • 7,170
  • 29
  • 46