Tuesday, September 3, 2013

JUnit Execution Procedure


JUnit Execution Procedure

Here is the execution procedure of methods in JUnit. Which means that which method is called first and which one after that.
1. @BeforeClass
2. @Before
3. @Test
4. @After
5. @AfterClass

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;


public class JunitExecutionProcedure {

    //Execute only once, in the starting
    @BeforeClass
    public static void beforeClass() {
         System.out.println("before class");
    }

    //Execute only once, in the end
    @AfterClass
    public static void afterClass() {
         System.out.println("after class");
    }

    //Execute for each test, before executing test
    @Before
   public void before() {
         System.out.println("before");
   }
 
    //Execute for each test, after executing test
    @After
    public void after() {
         System.out.println("after");
    }

    //Test case 1
   @Test
   public void testCase1() {
       System.out.println("test case 1");
   }

   //Test case 2
   @Test
   public void testCase2() {
        System.out.println("test case 2");
   }

   /**
    * @param args
    */
   public static void main(String[] args) {

        Result result = org.junit.runner.JUnitCore.runClasses(JunitExecutionProcedure.class);
        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }
        System.out.println(result.wasSuccessful());
   }
}