I have following class:
public class UsersHolder {
private Set<User> users = new HashSet<>();
public void addUser(User user) {
users.add(user);
}
...
}
users have not setter method
Is there way to test addUser
method?
There's a way.
@RunWith(MockitoJUnitRunner.class)
public class UsersHolderTest {
@InjectMocks private UsersHolder usersHolder;
@Mock private Set<User> users;
@Test
public void addUser_shouldAddUser() {
// given
User user = new User();
// when
usersHolder.addUser(user);
// then
Mockito.verify(usersHolder).add(user);
}
}
That being said I wouldn't test such a simple logic. Moreover in this case a set becomes a class dependency that should come from outside (usually collections are treated as data holders a managed inside the class).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.