Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

In this tutorial we will dive into JUnit5 framework even more basing on simple Calculator project that will grow with us during tutorial.


...

code
Info

The tutorial repository can be found here:

https://gitlab.eufus.eu/bpogodzinski/ach-tutorials/-/tree/TDD-java/TDD-java/Calculator


Project Structure:

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

...

Code Block
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());
    }

}

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


So let's write first simple test:

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

        assertEquals(EXPECTED,ACTUAL);
    }


Okey, we see the assert word, but what is that?


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. To keep things simple, all JUnit Jupiter assertions are static methods in the org.junit.jupiter.Assertions class. 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