How To Use JUnit Annotations In Java Project

There are lots of JUnit annotations. In this article, we will describe several JUnit annotations that frequently used in the java project. If you do not know how to add the JUnit framework libraries into your java project, please read How To Add JUnit 5 Dependency In Pom.xml first.

1. @Test Annotation.

  1. The @Test JUnit annotation is used to tell the JUnit framework that this annotated java method is a test method that needs to run.
     @Test
     public void runJUnitTest()
     {
         System.out.println("This runJunitTest.");
         long int1 = 1;
         long int2 = 2;
         Assert.assertEquals("1 dose not equal to 2", int1, int2);
     }
  2. To execute the above test method in eclipse, you need to right-click in your java class editor, select the Run As —> JUnit Test menu item in the popup menu list.

2. @Before Annotation.

  1. The @Before JUnit annotation decorates on a java method will execute this method before execute any test method.
     @Test
     protected void runJUnitTestAnnotation1()
     {
         System.out.println("This is runJUnitTestAnnotation1.");
     }
     
     @Test
     protected void runJUnitTestAnnotation2()
     {
         System.out.println("This is runJUnitTestAnnotation2.");
     }
     
     @Before
     protected void runJUnitBeforeAnnotation()
     {
         System.out.println("Execute before each test function.");
     }
  2. The output for the above code is:
    Execute before test function.
    This is runJUnitTestAnnotation1.
    Execute before test function.
    This is runJUnitTestAnnotation2.
  3. From the above output, we can see that the @Before annotated method will execute before each @Test annotated method.

3. @BeforeClass Annotation.

  1. If you add the @BeforeClass JUnit annotation to a java method then it will execute only once before all test method runs. This method must be static in the class. We always add java code to initialize database connection or read properties files in the @BeforeClass annotated java method.
  2.  @Test
     public void runJUnitTestAnnotation1()
     {
         System.out.println("This is runJUnitTestAnnotation1.");
     }
     
     @Test
     public void runJUnitTestAnnotation2()
     {
         System.out.println("This is runJUnitTestAnnotation2.");
     }
     
     @Before
     public void runJUnitBeforeAnnotation()
     {
         System.out.println("Execute before each test function.");
     }
     
     @BeforeClass
     public static void runJUnitBeforeClassAnnotation()
     {
         System.out.println("Execute beforeClass function only once when class is initialized.");
     }
  3. The output for the above code:
    Execute beforeClass function only once when class is initialized.
    Execute before each test function.
    This is runJUnitTestAnnotation1.
    Execute before each test function.
    This is runJUnitTestAnnotation2.

4. @After Annotation.

  1. The java method will be executed right after each test method runs if you add @After annotation to it.
  2.  @Test
     public void runJUnitTestAnnotation1()
     {
         System.out.println("This is runJUnitTestAnnotation1.");
     }
     
     @Test
     public void runJUnitTestAnnotation2()
     {
         System.out.println("This is runJUnitTestAnnotation2.");
     }
     
     @After
     public void runJUnitAfterAnnotation()
     {
         System.out.println("Execute after each test function.");
     }
  3. The output for the above code:
    This is runJUnitTestAnnotation1.
    Execute after each test function.
    This is runJUnitTestAnnotation2.
    Execute after each test function.

5. @AfterClass Annotation.

  1. Similar to the @BeforeClass annotation, the @AfterClass annotated method executes only once after all test methods executed. This annotated method should be static also.
     @Test
     public void runJUnitTestAnnotation1()
     {
         System.out.println("This is runJUnitTestAnnotation1.");
     }
     
     @Test
     public void runJUnitTestAnnotation2()
     {
         System.out.println("This is runJUnitTestAnnotation2.");
     }
     
     @After
     public void runJUnitAfterAnnotation()
     {
         System.out.println("Execute after each testing function.");
     }
     
     @AfterClass
     public static void runJUnitAfterClassAnnotation()
     {
         System.out.println("Execute afterClass function only once when all test methods executed.");
     }
  2. The output for the above java code:
    This is runJUnitTestAnnotation1.
    Execute after each testing function.
    This is a runJUnitTestAnnotation2.
    Execute after each testing function.
    Execute afterClass function only once when all test methods executed.

6. Use JUnit Annotation To Parameterized JUnit Class.

  1. Parameterized class in JUnit is a java class that can run exact same testing method using several datasets.
  2. We can use @RunWith and @Parameters JUnit annotation to implement this.
  3. You should add the @Parameters JUnit annotation to a java method which will return Collection<Object[]> data type data set.
  4. Then add the @RunWith(Parameterized.class) JUnit annotation to the JUnit test class.
  5. When you run the JUnit test class, the JUnit framework will pass the @Parameters annotated method returned collection data to the @RunWith(Parameterized.class) annotated JUnit test class to run.
  6. In the below example, the @Parameters annotated method is public static Collection<Object[]> parameter(), this method will return a two-dimension array that contains student name and score.
  7. The @RunWith(Parameterized.class) annotated JUnit java class is JUnitTestParameterizedClass, when the below java class executes, it will pass the above parameter() method returned two-dimension array to the JUnitTestParameterizedClass class.
    @RunWith(Parameterized.class)
    public class JUnitTestParameterizedClass {
     //name of the student.
     private String name;
    
     //age of the student.
     private int age;
    
     //Class constructor.
     public JUnitTestParameterizedClass(String name,int age){
         
        this.name=name;
         
        this.age=age;
     }
    
     //This is the function that will run for JUit.
     @Test
     public void testMethod(){
         System.out.println("Student Name is: "+name +" and student age is: "+age);
     }
    
     //This is the collection that save array data, we add @Parameters annotation to it.
     @Parameters
     public static Collection<Object[]> parameter(){
         //Init a 2*2 dimension data array.
         Object[][] pData=new Object[2][2];
     
         //Assign pData[0][0]'s value 
         pData[0][0]="Jerry";
     
         //Assign pData[0][1]'s value
         pData[0][1]=10;
     
         //Assign pData[1][0]'s value
         pData[1][0]="Jhon";
     
         //Assign pData[1][1]'s value
         pData[1][1]=15;
         
         return Arrays.asList(pData);
     }
    }
  8. The output of the above code:
    Student Name is: Jerry and student age is: 10
    Student Name is: Jhon and student age is: 15

7. How To Migrate JUnit 4 Code To JUnit 5.

  1. The newest JUnit version is JUnit 5, there are a lot of changes in JUnit 5.
  2. To use JUnit 5 you need first add the JUnit 5 jar libraries into your java maven project, you can read the article How To Add JUnit 5 Dependency In Pom.xml.
  3. All the above examples are based on JUnit 4, if you run them in JUnit 5, you will meet the error message like Class<> cannot be resolved to a type.
  4. To fix these errors, you can follow the below steps.
  5. Import the JUnit 5 class org.junit.jupiter.api.Test to fix the @Test annotation triggered error.
  6. Use JUnit 5 @BeforeAll ( import class org.junit.jupiter.api.BeforeAll ) to replace the @BeforeClass annotation.
  7. Use JUnit 5 @AfterAll ( import class org.junit.jupiter.api.AfterAll ) to replace the @AfterClass annotation.
  8. Use JUnit 5 @BeforeEach ( import class org.junit.jupiter.api.BeforeEach ) to replace the @Before annotation.
  9. Use JUnit 5 @AfterEach ( import class org.junit.jupiter.api.AfterEach ) to replace the @After annotation.
  10. Use JUnit 5 @ExtendWith( import class org.junit.jupiter.api.extension.ExtendWith ) to replace the @RunWith annotation.
  11. Use JUnit 5 @ParameterizedTest( import class org.junit.jupiter.params.ParameterizedTest ) to replace the @Parameterized.Parameters annotation.
  12. You can refer to the article https://stackoverflow.com/questions/46897134/how-to-implement-junit-4-parameterized-tests-in-junit-5.

8. Question & Answer.

8.1 How to get customized JUnit annotation annotated method coverage percentage in JUnit test suite.

  1. I create some custom JUnit annotations in my java project. And I add these customized JUnit annotations to some special java classes and java methods. But when I run the JUnit test suites in my java project, I do not know how many customized JUnit annotations annotated methods have been covered, passed, failed, not execute ( the test cases do not cover the annotated java classes or methods), etc. How can I get the customized JUnit annotation annotated java method coverage percentage and their status?
  2. You can use Google Reflections to do this. It can help you to analyze java classes and methods that are annotated by your own customized JUnit annotation in JAR files or java class files find in the path of the system environment variable classpath.
  3. Now you can generate the JUnit test suite execution report in XML format and then you can compare the XML result with google reflections returned methods( annotated with your own JUnit annotation ) to check whether all the annotated classes or methods have been covered in your JUnit test cases.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.