In this tutorial we will dive into JUnit5 framework even more basing on simple Calculator project that will grow with us during tutorial.
...
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 |
...
JUnit 5 assertions help in validating the expected output with actual output of a testcase. (The order is always the same!!)
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
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.
Code Block |
---|
@Test
@DisplayName("Divide by 0")
void divideBy0ExpectedExceptionTest() {
assertThrows(ArithmeticException.class, () -> {
Calculator.divide(8.0,0.0);
}); |