How to use Annotations in Junit

In the previous article, we learned about all the Assertion methods in JUnit https://codedec.com/tutorials/assertion-in-junit-framework/.  In this article, we will look at all the JUnit Annotations.

What is JUnit Annotation?

As we know, annotations are metadata that is added in a code to make it more readable. In the same way, we have annotations in JUnit which were introduced in JUnit version 4. JUnit has a list of annotations that will help to test a code more easily(and also make things simple for developers) and they are:

  • @Test
  • @Before
  • @After
  • @BeforeClass
  • @AfterClass

List of Annotations in JUnit

Let us see the annotations in JUnit with proper descriptions:

@Test: This is attached to a method to run a test case. JUnit first constructs an instance of the class then calls the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure. If no exceptions are thrown, the test is assumed to have succeeded.

By default, it contains the fail() method that would actually fail the test.

package in.codedec.junit.util;

import static org.junit.Assert.*;

import org.junit.Test;

public class Example {

    @Test
    public void test() {
        fail("Not yet implemented");
    }
}

@Before: Sometimes when executing test cases, we have to do some predefined setup. And the setup can be common to all the methods in a particular class. So, here we can use @Before Annotation. It is run before every test case.

package in.codedec.junit.util;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public class Example {

    @Before
    public void beforeTest(){
        System.out.println("@Before: run before the test method");
    }
    
    @Test	
    public void test() {
        fail("Not yet implemented");
    }

}

@After: @After is an annotation that is run after the @Test method. It is run after every test case is executed.

package in.codedec.junit.util;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Test;

public class Example {
    @Test	
    public void test() {
        fail("Not yet implemented");
    }
    
    @After
    public void afterTest(){
        System.out.println("@After: run after the test method");
    }

}

@BeforeClass: We want to do something before class once only so we can use @BeforeClass annotations.

Note: Any class which is annotated with @BeforeClass should be a static method. 

package in.codedec.junit.util;

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;

public class Example {
    @BeforeClass
    public static void beforeClassMethod(){
        System.out.println("@BeforeClass : runs once only per test class");
    }
    
    @Test	
    public void test() {
        fail("Not yet implemented");
    }

}

@AfterClass: The method annotated with this annotation is executed after all the test in the class has been run. For example, there can be a requirement where you want to release resources after all the method in the class has run. Here, we can use @AfterClass annotation.

Note: Any class which is annotated with @AfterClass should be a static method. 

package in.codedec.junit.util;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.Test;

public class Example {
        
    @Test	
    public void test() {
        fail("Not yet implemented");
    }
    @AfterClass
    public static void afterClassMethod(){
        System.out.println("@AfterClass : runs only once after all the test class");
    }

}

How to use Annotations in Junit

Example of JUnit Annotation

Here, we will do a practical implementation of JUnit Annotation. We will use @Before, @After, @BeforeClass, and @AfterClass.

In this example, we will create a JUnit Test Case to check if the number is a palindrome or not.

Step 1: Open Eclipse > File > New > Maven Project.

Step 2: Now, you will get a New Maven Project. Check the create a simple project. Click on Next.

Step 3: Now, Enter group id, artifact id as shown below

Step 4: Now, create a PalindromeUtil.java class inside the src/main/java folder.

package in.codedec.junit.util;

public class PalindromeUtil {

    public static String isPalindromeNumber(int num) {

        int rem, sum = 0, temp = 0;
        //assign num value to temp
        temp = num;
        while(num > 0){
            //get the remainder
            rem = num % 10;
            sum = (sum * 10) + rem;
            num = num / 10;
        }
        if(temp == sum){
            return "It is a palindrome";
        }
        else{
            return "It is not a palindrome";
        }
    }
    
}
  • Here, in this class, we created a method called isPalindromeNumber() that will check if the number is palindrome or not.
  • The method is returning a string value.

Step 5: Now, it is time to check this method. So we will create our  JUnit Test case. Here, we will keep our test file in a separate package. Mostly, we keep the test case file inside src/test/java. After that, click Finish. After Finish you will get the alert box, just click OK.

Step 6: Now, we will get the default test case generated and we will modify the code as shown below

package in.codedec.junit.util;

import static org.junit.Assert.*;

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

public class PalindromeUtilTest {
    @BeforeClass
    public static void beforeClass(){
        System.out.println("@BeforeClass executed");
    }
    @Before
    public void before(){
        System.out.println("@Before executed");
    }
    @Test
    public void test() {
        assertEquals("It is a palindrome", PalindromeUtil.isPalindromeNumber(151));
    }
    @After
    public void after(){
        System.out.println("@After executed");
    }
    @AfterClass
    public static void afterClass(){
        System.out.println("@AfterClass executed");
    }
}
  • Here, we have used all the annotation that has been discussed above.
  • The isPalindromeNumber() method is passed with 151. This method will return the string that will be an actual output. The expected value is “It is a palindrome”
  • Now, On-line no:22, the assertEquals() method is called with both expected and actual output. It will check if both the values match then the test case is run successfully with 0 failures.

Step 7: Now, Run the Application as Junit Test and see the following stack trace as well as the console.

Here, we can see the green bar that implies the test is run without error. Also, we can see the order of execution of annotation of JUnit.

Note: We are not showing the Failure case because the motive of this article is to understand the JUnit Annotations.

Thus, in this way, we learned how to use annotations in JUnit to make things simple and easy for us as a developer.