Different Annotations in JUnit Framework


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:

Basic JUnit Annotations
  1. @Test : This annotation marks the java method as a Test case.
  2. @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
  3. @Before : The method annotated with @Before must be executed before each test in the class.
  4. @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
  5. @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.
  6. @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<String> list; @BeforeClass public static void executedOnceBeforeAll() { System.out.println("@BeforeClass: executedOnceBeforeAll"); } @Before public void executedEverytimeBeforeEachTest() { list = new LinkedList<String>(); 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"); } }


@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.


Want to Clear Java Interview? Read Java Interview Notes prepared by Us

Are You Good enough in Java? Prove it!


Get Answers to your Programming Questions

Recommended Deals ends in

Quiz For You:

Search Tags

    JUnit Annotations

    Basic JUnit Annotations meaning

    What are basic JUnit Annotations

    Execution order of JUnit Annotations