Thursday, February 20, 2014

Java junit lifecycle methods

 JUnit is more popular framework for unit testing in java.  JUnit provide four life cycle methods for each test case class.

 @BeforeClass and @AfterClass anotation used before methods which are called by framework once for all test case.

@Before  and @After are used on methods which are called before and after any test method run.

Here is an example code snippet.



package com.test;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class ExampleTest {

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
  
  System.out.println("Before all test case execution");
 }

 @AfterClass
 public static void tearDownAfterClass() throws Exception {
   System.out.println("After all test case execution");
 }

 @Before
 public void setUp() throws Exception {
    System.out.println("Before single test case execution");
 }

 @After
 public void tearDown() throws Exception {
  System.out.println("After single test case execution");
 }

 @Test
 public void testMethod1() {
   System.out.println("a");
 }

 @Test
 public void testMethod2() {
   System.out.println("b");
 }

}


Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: BB (forum) link code:

No comments:

Post a Comment