Ali Hamadi Ali Hamadi - 1 month ago 26
Java Question

assertEquals testng doesn't work

I have the following code below:

@Test
public void testobjects(){
Country objExpected=new Country();
//objExpected.countryCode="34";
//country1.countryName="Blgaria";
//country1.id=1;
//country1.shortCountryCode="4";

Country objActual=new Country();
//country2.countryCode="34";
//country2.countryName="Blgaria";
//country2.id=1;
//country2.shortCountryCode="4";
Assert.assertEquals(objExpected, objActual);

}


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

thanks

Answer

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
            return this.id;
        }
    }