12:49 pm - Saturday July 22, 2017

Assert Example with JUNIT

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

JUnit Assertion

All the assertion are in the Assert class.

Public class Assert extends java.lang.Object.

This class provides a set of assertion methods useful for writing tests.

Assertion Methods are,

1. assertEqual(expected output,actual output),

2.assertTrue(boolean condition),

3.assertFalse(boolean condition),

4.assertNotNull(Object object),

5.assertNull(Object object),

6.assertSame(boolean condition),

7.assertNotSame(boolean condition),

8. assertArrayEqual(expected array,actual array)

Example Program,

import org.junit.Test;
import static org.junit.Assert.*;

public class JuTest {

@Test

   public void testAssertions() {

      String s1 = new String ("am string");
      String s2 = new String ("am string");
      String s3 = null;
      String s4 = "abc";
      String s5 = "abc";

      int a = 1;
      int b = 2;

      String[] a1 = {"hi", "hello"};
      String[] a2 =  {"hi", "hello"};

    //USING ASSERT

      assertEquals(s1,s2);   //Check equality
      assertTrue (a < b);   //Check true condition
      assertFalse(a > b);   //Check false condition
      assertNotNull(s1);      //Check Notnull
      assertNull(s3);  //Check null
      assertSame(s4,s5);  //Check same object
      assertNotSame(s1,s4);  //Check  Notsame object
      assertArrayEquals(a1,a2);  //Check ArrayEquality

   }
}

Note:Save above the program JuTest.java and below program Junit

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class Junit

{

   public static void main(String[] args)
{

      Result result = JUnitCore.runClasses(JuTest.class);

      for (Failure failure : result.getFailures())
      {
    	  System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }

}

Output

true

BACK

Filed in: Z-A All Java Codes

Comments are closed.