JUnit 5 Simple example

In this post under JUnit 5, I will introduce to new version of JUnit with simple example.

JUnit 5 is divided into three subprojects as shown below

JUnit Platform –> This is the base subproject on which other subproject depends. It has TestEngine API which will be implemented by other subprojects. Its main purpose is to launch JVM testing frameworks.

JUnit Jupiter –> This subproject is used to write JUnit 5 test cases. It provides sdk for writing test cases and also provides JUnit5 specific implementation of TestEngine API available in JUnit Platform

JUnit Vintage –> This subproject is mainly to provide backward compatibility to JUnit 3 and 4 test cases. It also implements TestEngine API which will execute JUnit 3 and 4 test cases.

For our example we will create a “Calculator” class as shown below

Calculator class


package package1;

public class Calculator {
    private int x, y;

    public int add() {
        return x + y;
    }

    public int sub() {
        return x - y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

In the above code, we have created a “Calculator” class. It has two calculator methods “add” and “sub”. We will write test cases for them.

Below is the test class

CalculatorTest class


1  package package1;
2  
3  import static org.junit.jupiter.api.Assertions.assertEquals;
4  
5  import org.junit.jupiter.api.Test;
6  
7  class CalculatorTest {
8  
9      private Calculator calculator = new Calculator();
10     
11     @Test
12     void testAdd() {
13         calculator.setX(5);
14         calculator.setY(10);
15         
16         assertEquals(15, calculator.add());
17     }
18 }

In pre JUnit 5, test classes and methods had to be declared public but post JUnit 5 those restrictions are removed. In the above code, the class and test method are declared with “default” access instead of “public” access. Refer to line 7 and 12. The test methods can be declared with public, protected, and default access. The test class can be declared with public and default access.

In pre JUnit 5, we had to have classes with public no argument constructor but post JUnit 5 that restriction is removed. We can have constructor with default, protected, and private access. We can also have constructor with arguments.

The test methods are annotated with @Test annotation. Please note we are not using JUnit 4 @Test annotation, this new annotation belongs to “org.junit.jupiter.api” package whereas JUnit 4 @Test annotation belongs to “org.junit” package.

Next at line 16, we add assert method to compare the returned value of “add” method with the expected value. Please note this is also from new “org.junit.jupiter.api.Assertions” package.

In this way we have to write JUnit test cases in JUnit 5.

Leave a Reply