user2297666
user2297666

Reputation: 321

Junit Testing with an Array List

I have a method set up to add users to an ArrayList, and return false if the same user is added:

public boolean addUser(K pass, V user)
{
    if (username.contains(user))
    {
        return false;
    }
    else
    {
        password.add(pass);
        username.add(user);
        size++;
        return true;
    }
}

Then I have a JUnit test to assertFalse(true) because that's what my method returns when adding two users with the same name:

@Test
public void testAddingTwoOfTheSameUserToArrayList() {
    User<String, String> user1 = new User<String, String>();
    user1.addUser("password", "SpeedinDave");
    user1.addUser("password", "SpeedinDave");
    assertFalse(true);
}

However, it the test always turns up false (red bar). Any ideas?

Upvotes: 0

Views: 1362

Answers (2)

Mark
Mark

Reputation: 31

Right now you are not testing the return value of your addUser() method, but rather that the boolean constant true evaluates to false (this will never be true). You probably want something like:

@Test
    public void testAddingTwoOfTheSameUserToArrayList() {
        User<String, String> user1 = new User<String, String>();
        assertTrue(user1.addUser("password", "SpeedinDave"));
        assertFalse(user1.addUser("password", "SpeedinDave"));
    }

Upvotes: 3

eternay
eternay

Reputation: 3814

You should test something like that:

@Test
    public void testAddingTwoOfTheSameUserToArrayList() {
        User<String, String> user1 = new User<String, String>();
        user1.addUser("password", "SpeedinDave");
        assertFalse(user1.addUser("password", "SpeedinDave"););
    }

to be sure that the second addUser() returns false.

assertFalse(b) will succeed if the parameter b is false. So if you pass true, it will always fail.

Upvotes: 8

Related Questions