In this tutorial we will dive into JUnit5 framework even more basing on very simple Calculator project.


The tutorial repository can be found here:

https://gitlab.eufus.psnc.pl/ach/ach-tutorials

Project Structure:

.
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── Calculator.java
    └── test
        └── java
            └── CalculatorTest.java

Our Calculator.java  look like this:

As you can see it has only divide() method, that checks if b is equal to 0. If it is, it throws an exception.

public class Calculator {

    static Double divide(Double a, Double b) {
        if (b != 0) {
            return a / b;
        }
        else{
            throw new ArithmeticException("Division by 0 is impossible!");
        }
    }

    public static void main(String[] args) {
        System.out.printf(Calculator.divide(8.0,2.0).toString());
    }

}

So let's write first simple test, but before that we need to know what the assertion are.

Assertions 

Assertion is a statement in java. It can be used to test your assumptions about the program.

JUnit 5 assertions help in validating the expected output with actual output of a testcase. (The order is always the same!!)

List of every possible assertions is here: https://junit.org/junit5/docs/5.7.2/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html

So our test class looks like this:

 @Test
    @DisplayName("Divide two finite numbers")
    void divideTest() {
	     
         final double EXPECTED = 4;
         final double ACTUAL = Calculator.divide(8.0,2.0);

        assertEquals(EXPECTED,ACTUAL);
    }

Exceptions

To ensure our error handling works correctly, we can verify that a piece of code throws a specific exception under certain conditions.

This can be done with the assertThrows() method in JUnit 5: If we catch this thrown exception test is passed.


    @Test
    @DisplayName("Divide by 0")
    void divideBy0ExpectedExceptionTest() {
        assertThrows(ArithmeticException.class, () -> {
            Calculator.divide(8.0,0.0);
        });

The scientific work is published for the realization of the international project co-financed by Polish Ministry of Science and Higher Education in 2019 from financial resources of the program entitled "PMW"; Agreement No. 5040/H2020/Euratom/2019/2

This work has been carried out within the framework of the EUROfusion Consortium and has received funding from the Euratom research and training programme 2014–2020 under grant agreement No 633053. The views and opinions expressed herein do not necessarily reflect those of the European Commission or ITER

  • No labels