To validate arguments to methods called on a mock, use the ArgumentCaptor
class. This will allow you to extract the arguments into your test method and perform assertions on them.
This example tests a method which updates the name of a user with a given ID. The method loads the user, updates the name
attribute with the given value and saves it afterwards. The test wants to verify that the argument passed to the save
method is a User
object with the correct ID and name.
// This is mocked in the test
interface UserDao {
void save(User user);
}
@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
@Mock
UserDao userDao;
@Test
public void testSetNameForUser() {
UserService serviceUnderTest = new UserService(userDao);
serviceUnderTest.setNameForUser(1L, "John");
ArgumentCaptor<User> userArgumentCaptor = ArgumentCaptor.forClass(User.class);
verify(userDao).save(userArgumentCaptor.capture());
User savedUser = userArgumentCaptor.getValue();
assertTrue(savedUser.getId() == 1);
assertTrue(savedUser.getName().equals("John"));
}
}