assertEqual vs assertSame in testng

In Junit and TestNG, you will see these 2 methods of Assert class. In case of assertEquals, it compares 2 reference variables by calling the equals method of the object. In this case, reference variables may point to same object or different objects. If 2 reference variables point to same object, it returns true. If 2 reference variables point to different objects, it may or may not return true based upon implementation of equals method of the objects they point to. So there can be a possibility that 2 different objects may be equal depending upon definition of equals method In case of assertSame, it compares if the reference variables point to same object. In this case, It will return true if and only if both variable point to same object otherwise it returns false Here is the example that explains the difference.
 
package org.softpost;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestNGAssertions1 {

    @Test
    public void testAssertions(){

        Student s1 = new Student();
        s1.name = "watson";
        Student s2 = s1;

        //below assertions is successful as s1 and s2 point to same object
        Assert.assertEquals(s1,s2);

        //below assertions is successful as s1 and s2 point to same object
        Assert.assertSame(s1, s2);

        Student s3 = new Student();
        s3.name = "Shaun";

        //below assertions is unsuccessful as equals method of s1 returns false
        Assert.assertEquals(s1,s3);

        //below assertions is unsuccessful as s1 and s3 point to different object
        Assert.assertSame(s1,s3);

        s3.name = "watson";
        //below assertions is successful as equals method of s1 returns true
        Assert.assertEquals(s1,s3);

        //below assertions is unsuccessful as s1 and s3 are different objects
        Assert.assertSame(s1,s3);
    }
}

class Student{
    String name;

    @Override
    public boolean equals(Object obj) {
        if (this.name.equalsIgnoreCase(((Student)obj).name))
        {
            return true;
        }else
            return false;
    }
}                    

Web development and Automation testing

solutions delivered!!