JUnit - Execution Procedure

This chapter explains the execution procedure of methods in JUnit, which defines the order of the methods called. Discussed below is the execution procedure of the JUnit test API methods with example.

Create a java class file named ExecutionProcedureJunit.java to test annotation.
public class ExecutionProcedureJunit {
 
   //execute only once, in the starting 
   @BeforeClass
   public static void beforeClass() {
      System.out.println("in before class");
   }

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

   //execute for each test, before executing test
   @Before
   public void before() {
      System.out.println("in before");
   }
 
   //execute for each test, after executing test
   @After
   public void after() {
      System.out.println("in after");
   }
 
   //test case 1
   @Test
   public void testCase1() {
      System.out.println("in test case 1");
   }

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

Next, create a java class file named TestRunner.java to execute annotations.
public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(ExecutionProcedureJunit.class);

      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
  
      System.out.println(result.wasSuccessful());
   }
} 
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
Verify the output.
in before class
in before
in test case 1
in after
in before
in test case 2
in after
in after class

See the above output. The execution procedure is as follows −
  1. First of all, the beforeClass() method executes only once.
  2. The afterClass() method executes only once.
  3. The before() method executes for each test case, but before executing the test case.
  4. The after() method executes for each test case, but after the execution of test case.
  5. In between before() and after(), each test case executes.









No comments:

Post a Comment