java.lang.AssertionError: expected

14,963

The reason is simple. Testng uses the equals method of the object to check if they're equal. So the best way to achieve the result you're looking for is to override the equals method of the user method like this.

public class User {
    private String lastName; 
    private String firstName;
    private String userId;

    // -- other methods here

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (!User.class.isAssignableFrom(obj.getClass())) {
            return false;
        }

        final User other = (User) obj;


        //If both lastnames are not equal return false
        if ((this.lastName == null) ? (other.lastName != null) : !this.lastName.equals(other.lastName)) {
            return false;
        }

        //If both lastnames are not equal return false
        if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)) {
            return false;
        }

        //If both lastnames are not equal return false
        if ((this.userId == null) ? (other.userId != null) : !this.userId.equals(other.userId)) {
            return false;
        }       

        return true;
    }
}

and it'll work like magic

Share:
14,963
Qube Square
Author by

Qube Square

Updated on June 04, 2022

Comments

  • Qube Square
    Qube Square almost 2 years

    My TestNG test implementation throws an error despite the expected value matches with the actual value.

    Here is the TestNG code:

    @Test(dataProvider = "valid")
    public void setUserValidTest(int userId, String firstName, String lastName){
        User newUser = new User();
        newUser.setLastName(lastName);
        newUser.setUserId(userId);
        newUser.setFirstName(firstName);
        userDAO.setUser(newUser);
        Assert.assertEquals(userDAO.getUser().get(0), newUser);
    }
    

    The error is:

    java.lang.AssertionError: expected [UserId=10, FirstName=Sam, LastName=Baxt] but found [UserId=10,   FirstName=Sam, LastName=Baxt]
    

    What have I done wrong here?