AssertSame Example

In this post under JUnit, I will show with example the purpose of AssertSame assertion method.

JUnit 5 has added new assertion method “assertSame” that checks for Object reference equality.

How “assertSame” is different from “assertEquals” assertion method is that latter check for Object value equality whereas

former checks for Object reference equality.

Object value equality happens when two separate object happen to have the same values/state.

Object reference equality happens when two object references point to the same object.

The method signature is shown below


    public static void assertSame(Object expected, Object actual)

Below is an Java example for your reference

We use the below class for our equality testing

Cat


package package11;

public class Cat {
    private String name;
    private String color;

    public Cat(String name, String color) {
        this.name = name;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public String getColor() {
        return color;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj == null)
            return false;
        if (!(obj instanceof Cat)) {
            return false;
        }
        Cat cat = (Cat)obj;
        if(this.name.equals(cat.getName()) && this.color.equals(cat.getColor())) {
            return true;
        } else {
            return false;
        }
    }
}

As you can see in the above code, we declare a class named “Cat” and it has two properties named “name” and “color”.

This class also override the “equals” method.

Below is the test class that will actually do the equality testing

Test Class


1  package package11;
2  
3  import static org.junit.jupiter.api.Assertions.assertEquals;
4  import static org.junit.jupiter.api.Assertions.assertSame;
5  
6  import org.junit.jupiter.api.Test;
7  
8  public class CatTest {
9      @Test
10     public void testAssertSame() {
11         Cat cat1 = new Cat("Jimmy", "Black");
12         Cat cat2 = new Cat("Jimmy", "Black");
13         Cat cat3 = cat1;
14         
15         assertSame(cat1, cat3);
16         assertEquals(cat1, cat2);
17         assertSame(cat1, cat2);
18     }
19 }

In the above class, at line 11 and 12, we create two instances of “Cat” with same field values.

At line 13, we assign “Cat” instance “cat1” to another “Cat” variable named “cat3”.

At line 15, we use assertSame on cat1 and cat3. The assert will be successful because of Object reference equality.

At line 16, we use assertEquals on cat1 and cat2. The assert will be successful because of Object value equality.

At line 17, we use assertSame on cat1 and cat2. The assert will fail because of not satisfying Object reference equality.

Leave a Reply