Reputation: 1147
I have the following test :
@Test
public void deleteUser(){
User user = new User("admin","admin");
service.createUser(user);
service.deleteUser(1);
assertTrue("Check that user is deleted: ", user.getId() < 1);
}
But it gives me AssertationError. Why can I not do like that? I create my user and then wanna test that I am able to delete the newly created user.
My delete method is just deleting from a hashmap the user.
Map<Long, User> users = new HashMap<Long, User>();
protected static long nextId = 0;
@Override
public long createUser(User user) {
user.setId(getNextId());
users.put(user.getId(), user);
return user.getId();
}
@Override
public void deleteUser(long id) {
users.remove(id);
}
Can somebody explain this to me?
Upvotes: 0
Views: 152
Reputation: 103
Your test does not make any sense - you want to check if the user is deleted from the service, but instead you are checking the value of the Id property of the user object (which is null, or set to some value - you did not provide any code). As some users already suggested, you need to check if the user is actually contained within your service. Also, are you doing something inside your getNextId() method? If that is simply getter for your nextId variable, every single user you create will have Id set to 0 (but maybe you wanted it that way, who knows). Is there some code within getNextId that actually sets the value to something else?
Upvotes: 0
Reputation: 1102
Instead of accessing the User
object, that you still have the reference to (independent of whether it's deleted), you should implement a method, that checks, whether a user is present in the class of your service variable:
public boolean containsUser(long userId) {
return users.containsKey(userId);
}
And then assert like so:
assertFalse("Check that user is deleted: ", service.containsUser(1L));
Upvotes: 1
Reputation: 718
When you delete user from Map
, you do nothing with user.id
. That's why your assertion fails.
One way to change id when deleting
@Override
public void deleteUser(long id) {
User deletedUser = users.remove(id);
deletedUser.setId(-1);
}
Another (and better) way is to change test:
@Test
public void deleteUser(){
User user = new User("admin","admin");
long id = service.createUser(user);
service.deleteUser(id);
assertFalse("Check that user is deleted: ", service.hasUser(id));
}
Upvotes: 0