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 {
    @Test
    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", "softpost.org","softpost.org");
        int [] a1 = {22,33};
        int [] b1 = {22,33};
        Assert.assertArrayEquals(a1,b1);

        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!!