JUnit — Using Annotation

Emre Dogangun
2 min readMay 24, 2024

What is JUnit?

It is an open source framework for writing and running unit tests in Java.

For detailed information, you can go to this resource.

Annotations are like meta tags that you can add to your code and apply them to methods or class. These annotations in JUnit provide the following information about test methods -

  1. Information is given about which methods will work before and after the test methods.
  2. Information is given which methods run before and after all methods.
  3. Information is given which methods or classes to ignore during execution.

The following post provides a list of annotations and their meaning in JUnit.

Annotation

1.@Test

Annotation used in JUnit to indicate that a function is written for testing purposes

2.@Before

Annotation used in JUnit to create the same values and objects that multiple test methods would need in a test class before the tests run.

3.@After

Annotation used in JUnit to run some common code in a test class after more than one test method has run. For example, releasing some resources etc. is done with this method.

4.@BeforeClass

In JUnit, annotation is used to define the method in which the work that needs to be done before the test methods in a test class are started.

5.@AfterClass

In JUnit, annotation is used to define the method in which the work that needs to be done after all the test methods in a test class are completed.

6.@Ignore

Annotation used to not run a test method. Instead of deleting or commenting on a test block, it is sufficient to add @Ignore to the beginning.

To test the annotation, create a Java class file named JunitAnnotation.java.

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class JunitAnnotation {

//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");
}
}

Next, run the test cases.
Verify the output.

in before class
in before
in test
in after
in after class
true

You can click on this link to access the project.

--

--