JUnit 5 – Assertions and Assumptions. Part 1

JUnit 5 – Assertions and Assumptions. Part 1

Abstract: JUnit is a unit testing framework for the Java programming language. The JUnit 5 version has been redesigned to solve some particular problems of the previous versions. It comes with a new architecture, and with a lot of new features. Additionally to the ones presented in our previous article, we’ll discuss here in more detail assertions and, assumptions.

 

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:

Assertions in JUnit 5.png

The message in assertions is the last parameter of the methods:

static void.JPG

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:

assertions.JPG

test_junit5.JPG

test_junit5_private.JPG

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:

assertAll.JPG

This is how the usage of the assertAll methods may look like:

assertAll methods.JPG

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:

assertTimeout methods.JPG

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:

static T extends.JPG

This is how the usage of the assertThrows method may look like:

assertThrows_1.JPG

assertThrows_2.JPG

Interested in JUnit?

Check out our trainings
Tudose, Florin-Catalin , Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin Tudose author linkedin

Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin , Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin Tudose author linkedin

Java Champion; Java Chapter Lead; Author at Pluralsight and Manning