Execution order of JUnit annotations

In this blogpost, we will focus on understanding the order of execution of annotations provided by JUnit API.

JUnit supports 5 main annotations, listed as per the execution order.

Annotation Syntax Execution order
@BeforeClass public static void Executed before the first @Test method in JUnit test class
@Before public void Executed before all the @Test methods
@Test public void Executed for all @Test methods
@After public void Executed after all @Test methods
@AfterClass public static void Executed after all the @Test methods in the JUnit test class

Let us understand the execution order of all 5 annotations with a simple program.

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

public class ExecutionOrderOfAnnotations {

@BeforeClass
public static void beforeClassMethod() {
System.out.println(“Inside Before Class method”);
}

@Before
public void beforeMethod() {
System.out.println(“Inside Before Method”);
}

@Test
public void test() {
System.out.println(“Inside Test method”);
}

@After
public void afterMethod() {
System.out.println(“Inside After method”);
}

@AfterClass
public static void afterClassMethod() {
System.out.println(“Inside After Class method”);
}

}

And the result looks as below.

Inside Before Class method
Inside Before Method
Inside Test method
Inside After method
Inside After Class method

Advertisements

#after, #afterclass, #before, #beforeclass, #test, #execution-order-of-junit-annotations, #junit-annotations