Java JUnit Tutorial - JUnit Annotation








Annotations are meta-tags we can use to mark methods or classes.

We can annotations from JUnit to mark methods. For example, we can use @Before to mark a method to run before the test cases.

Annotations

The following table lists annotations and their meaning in JUnit.

AnnotationDescription
@Testmarks the public void method as a test case.
@BeforeAnnotating a method with @Before causes that method to be run before each Test method.
@AfterAnnotating a method with @After causes that method to be run after the Test method.
@BeforeClassAnnotating a method with @BeforeClass causes it to be run once before any of the test methods in the class.
@AfterClasscall the method after all tests have finished.
@Ignoremarks to ignore the test and that test will not be executed.




Example

The following code shows how to use annotations introduced above.

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
//  ww  w. j ava 2 s  .c  om
public class TestJunit {
  // execute before class
  @BeforeClass
  public static void beforeClass() {
    System.out.println("in before class");
  }

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

  // execute before test
  @Before
  public void before() {
    System.out.println("in before");
  }

  // execute after test
  @After
  public void after() {
    System.out.println("in after");
  }

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

  // test case ignore and will not execute
  @Ignore
  public void ignoreTest() {
    System.out.println("in ignore test");
  }
}




Run

The following code shows how to run the code above.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
// www.  j  a v  a 2s.  c o  m
public class Main {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

The code above generates the following result.

Example 2

The following code shows how to ignore a test case

import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit {

  
   @Ignore
   @Test
   public void testPrintMessage() {
      ...
   }

   @Test
   public void testSalutationMessage() {
     ...
   }
}

We can also provide message for the @Igore message.

  @Ignore("Not Ready to Run")  
  @Test
  public void divisionWithException() {  
    System.out.println("Method is not ready yet");
  }