Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.AssertionError: expected

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?

like image 337
Qube Square Avatar asked Jun 20 '26 09:06

Qube Square


1 Answers

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

like image 196
Aryeetey Solomon Aryeetey Avatar answered Jun 22 '26 13:06

Aryeetey Solomon Aryeetey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!