Supossing I have the following code to test UserController
by mocking UserService
(where UserController
has a reference to UserService
):
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
...
public class UserControllerTest {
private final List<User> users1 = new ArrayList<>();
private final List<User> users2 = new ArrayList<>();
@Before
public void initUsers() {
User user = new User();
user.setId(1L);
users1.add(user);
User user = new User();
user.setId(2L);
users2.add(user);
}
@Test
public void testFindAlls() throws Exception {
UserService userService = mock(UserService.class); //line1
when(userService.findAll1()).thenReturn(users1); //line2
when(userService.findAll2()).thenReturn(users2); //line3
UserController userController = new UserController();
ReflectionTestUtils.setField(userController, "userService", userService);
List<User> users3 = userController.findAll1(); //line4
List<User> users4 = userController.findAll2(); //line5
...
}
}
I have the following doubts:
- When the line1 is reached, what would be the default behaviour for
userService.findAll1()
anduserService.findAll2()
? - When the line3 is reached, as
userService.findAll1()
anduserService.findAll2()
return the same result type (List<User>
). Will the line3 override the behaviour defined in line2? I mean, willuserService.findAll1()
returnusers2
instead ofusers1
? - I mean, the
when
method signature ispublic static <T> OngoingStubbing<T> when(T methodCall)
soT
in the example would be an element of typeList<User>
with the value probably tonull
. So, how thewhen
method is able to determine that different calls are passed as arguments?