Time to focus on the new Junit 5 approach in our second article of the series where we talk about migrating from JUnit 4 to JUnit 5. Check it out.
Listing 3 The JUnit5ExceptionTester class
In this JUnit 5 example, we do the following:
- We initialize an instance of the Calculator class whose functionality we are testing (1’).
We assert that the execution of the supplied calculator.sqrt(-1) executable throws an IllegalArgumentException (2’).
We assert that the execution of the supplied calculator.divide(1, 0) executable throws an ArithmeticException (3’).
We remark the clear difference in code clarity and code length between JUnit 4 and JUnit 5. The effective testing JUnit 5 code is 13 lines, the effective JUnit 4 code is 20 lines. We do not need to initialize and manage any additional rule. The testing JUnit 5 methods contain one line each.
Testing temporary folders
Another largely used rule is TemporaryFolder
. The TemporaryFolder
rule allows the creation of files and folders that should be deleted when the test method finishes (whether it passes or fails). The JUnit 4 rule has been replaced with the @TempDir
annotation in JUnit 5. Listing 4 presents the JUnit 4 approach.
Listing 4 The JUnit4RuleTester class
In this example, we do the following:
- We declare a TemporaryFolder field annotated with @Rule and initialize it. The @Rule annotation must be applied either on a public field or on a public method (1).
We use the TemporaryFolder field to create a folder and a file (2). These ones are to be found into the Temp folder of your user profile into the operating system.
We check the existence of the temporary folder and of the temporary file (3).
Now, we move our attention to the new JUnit 5 approach (listing 5).
Listing 5 The JUnit5TempDirTester class
Into the previous JUnit 5 example, we do the following:
- We declare a @TempDir annotated field (1’).
We check the creation of this temporary directory before the execution of the test (2’).
We create a file within this directory and check its existence (3’).
The advantage of the JUnit 5 extension approach is that we do not have to create the folder by ourselves through a constructor, but the folder is automatically created once we annotate a field with @TempDir
Interested in JUnit? Check out our trainings.
Java and Web Technologies Expert