JUnit 5 Assertions and Assumptions. Part 1
1. Assertions in JUnit 5
JUnit Jupiter comes with more assertion methods that JUnit 4 does. It adds a few that lend themselves well to being used with Java 8 lambdas. All JUnit Jupiter assertions are static methods in the org.junit.jupiter.api.Assertions class.
A comparison between assertions in JUnit 4 and JUnit 5 looks like this:
The message in assertions is the last parameter of the methods:
The Supplier allows for lazy initialization in case of complex messages.
This is how a piece of code using many of the possible assertions will look like:
The assertAll method will execute the checking of all assertions. It has an optional heading parameter. The heading parameter allows to recognize group of assertions within assertAll. The failure message of assertAll method shows detailed information about each and every field assertion within a group.
The methods are:
This is how the usage of the assertAll methods may look like:
The assertTimeout method is a replacement for the JUnit 4 Timeout Rule.
assertTimeout waits until the executable will finish. The failure message may looks like: execution exceeded timeout of 100 ms by 193 ms
assertTimeoutPreemptively stops the executable when the time passes. Failure message may looks like: execution timed out after 100 ms
This is how the usage of the assertTimeout methods may look like:
The assertThrows method is a replacement for the JUnit 4 ExpectedException Rule. All assertions can be made against the returned instance of a Throwable. This makes tests more readable. As executables we may use lambdas or methods references.
The method is:
This is how the usage of the assertThrows method may look like:
Interested in JUnit? Check out our trainings.
Java and Web Technologies Expert