Ali Hamadi Ali Hamadi - 1 year ago 102
Java Question

assertEquals testng doesn't work

I have the following code below:

public void testobjects(){
Country objExpected=new Country();

Country objActual=new Country();
Assert.assertEquals(objExpected, objActual);


when running the test, it fails!! could you please help me understand what am i doing wrong?


Answer Source

assertEquals method compares the two objects by verifying the equals() method. So, you need to override equals() and hashcode() methods inside the Country class to make the object comparison:

public class Country {

        public String countryCode;

        public int id;

        public String countryName;

        public String shortCountryCode;

        public boolean equals(Object obj) {

            //I have added country code, add other conditions 
            // which need to be part of equality check
            if(obj instanceof Country 
                && ((Country) obj).countryCode == this.countryCode) {
                return true;
            } else {
                return false;

        public int hashcode() {
            //I have added country code, add other required fields 
            // to generate the hashcode
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download