Assertions in junit

Assertions are used to decide if the test passes or fails. If the assertion is successful, test will pass. Otherwise it will fail. org.junit.Assert class provides various methods that can be used to do assertions in tests. There are various types of assertions in JUnit.
  • assertTrue and assertFalse – checks if expression returns true or false.
  • assertArrayEquals – checks if 2 arrays have equals values.
  • assertEquals – checks if 2 objects are equal.
  • assertNull and assertNotNull – checks if expression is null or not null.
  • assertSame and assertNotSame – checks if the 2 objects refer to same object.
  • assertThat – Asserts that actual satisfies the condition specified by matcher.
All above methods have various signatures. For example – assertTrue method has 2 signatures as mentioned below. In first method, we can pass the message which we want to print in the console output which can be used for troubleshooting.
assertTrue(String x, boolean y)
assertTrue(boolean y)

Similarly we have different signatures for all other methods. Here is an example which shows how to use assertions.
import org.junit.Assert;
import org.junit.Test;

public class Assertions {
    public void test1(){
        System.out.println("Running test1");
        Assert.assertTrue("Checking simple condition",1==1);
        Assert.assertFalse("Checking that expression is false",1==3);

        String a = null;
        Assert.assertNull("Assert if variable points to null",a );
        Assert.assertEquals("Assert if strings are same", "","");
        int [] a1 = {22,33};
        int [] b1 = {22,33};

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

        //below assertions is successful as s1 and s2 point to same object

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

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

        //below assertions is unsuccessful as equals method of s1 returns false

        //below assertions is unsuccessful as s1 and s3 point to different object
        Assert.assertSame(s1,s3); = "watson";
        //below assertions is successful as equals method of s1 returns true

        //below assertions is unsuccessful as s1 and s3 are different objects

class Student{
    String name;

    public boolean equals(Object obj) {
        if (
            return true;
            return false;

Web development and Automation testing

solutions delivered!!