Mocking Batch Saving in Mockito

In Mockito Answer, we mock the process.

Mock a single saving

Saving a new User object, means service accept a user without Id and will return a user with id to the front end. When we mockito it, we would do it this way:

when( Answer<String>() {
    public User answer(InvocationOnMock invocation) throws Throwable {
        User user = (User)invocation.getArguments()[0];
        return user;

Mock a batch saving

In order to improve performance, we sometimes like to use saveAll() method. So this time we pass in a list of Users, here is the answer:

    .thenAnswer(new Answer<List<User>>() {
        public List<User> answer(InvocationOnMock invocation) throws Throwable {
            List<User> users = (List)invocation.getArguments()[0];

            User user = users
                    .filter(user -> user.getId() == null)

            return users;