JUnit is the most popular Unit Testing Framework for Java programming language. It has been very important in the development of test-driven deployment. In this article, we will be giving you a fair understanding of different commonly used annotation in JUnit framework.
Some Basic JUnit Annotations every Java Developer should know:
- @Test : This annotation marks the java method as a Test case.
- @Ignore : This annotation is used either on a Java Test Class or individual Test methods. What @Ignore annotation specifies is that the compiler should ignore or skip the given Test class or Test method annotated with @Ignore
- @Before : The method annotated with @Before must be executed before each test in the class.
- @BeforeClass : This annotation indicates that the static method to which it is attached must be executed once and before all tests in the class. This annotation can only be applied to Static methods
- @AfterClass : This annotation indicates that the static method to which it is attached must be executed once and after all tests in the class are executed.
- @After : The After annotation indicates that this method gets executed after execution of each test.
Simple Junit Test Example :
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.*;
public class JunitExampleTest {
private LinkedList list;
@BeforeClass
public static void executedOnceBeforeAll() {
System.out.println("@BeforeClass: executedOnceBeforeAll");
}
@Before
public void executedEverytimeBeforeEachTest() {
list = new LinkedList();
System.out.println("@Before: executedEverytimeBeforeEachTest");
}
@Test
public void emptyCollection() {
assertTrue(list.isEmpty());
System.out.println("@Test: EmptyLinkedList");
}
@Test
public void oneItemCollection() {
list.add("A");
assertEquals(1, list.size());
System.out.println("@Test: OneItemLinkedList");
}
@Ignore
@Test
public void secondItemCollection() {
list.add("B");
assertEquals(2, list.size());
System.out.println("@Test: SeconditemLinkedList");
}
@AfterClass
public static void onceExecutedAfterAll() {
System.out.println("@AfterClass: onceExecutedAfterAll");
}
}
Output:
@BeforeClass: executedOnceBeforeAll
@Before: executedEverytimeBeforeEachTest
@Test: EmptyLinkedList
@Before: executedEverytimeBeforeEachTest
@Test: OneItemLinkedList
@AfterClass: onceExecutedAfterAll
From above example, you can check @BeforeClass and @AfterClass annotated methods ran only once while @Before annotated method ran twice. Also 1 test case was skipped as it was marked as @Ignore.