To continue the JUnit 5 tutorial series, I’d like to share about JUnit 5 exception testing, how JUnit 5 supports us in testing exception.

1. Preparation

The basic source code can be found in Github.

You will need to get JUnit 5 be ready in your environment. You can do it by yourselves or refer to my recent post which mentioned how to getting started with JUnit 5, how to set up JUnit 5 with Eclipse, Maven and Gradle.

You can also find all JUnit 5 tutorials at this page: JUnit 5 Tutorial

2. JUnit 5 Exception Testing

Let’s assume that we have a class StringUtils that has a method convertToInt to convert a given string into Integer. If the given string is Null or empty, then the method will throw an IllegalArgumentException with a message: “String must be not null or empty“.

We write some tests for this method to get to know about JUnit 5 exception testing

2.1. Using assertThrows annotation.

Let’s see the syntax of assertThrows in JUnit 5. This method is used to assert that the supplied executable will throw an exception of the expectedType. If there is no exception of expectedType is thrown, the method will failed.

For example, we will write a test method which we will call the StringUtils.convertToInt method and pass to it a Null parameter.

2.2. Using expectThrows annotation.

Let’s see the syntax of expectThrows  in JUnit 5

The expectedThrows method is almost similar to the assertThrows, except that this method returns the thrown exception.

For example, let’s try to test our method.

We can get back the exception and try to compare our expected error message with the actual message. The expectThrows is used to verify more detail of the thrown exception rather than just the type of exception as assertThrows method.

2.3. Using Try/Catch Idiom

One more way to do with JUnit 5 exception testing is to use try/catch idiom likes the previous version of JUnit.

Let’s see an example to test our convertToInt method.

3. An output on my Eclipse.

Below is the output of above tests on my Eclipse.

JUnit 5 Exception Testing

JUnit 5 Exception Testing

4. Conclusions

We have learned about JUnit 5 exception testing, how to use basic assertions like expectThrows and assertThrows to test exceptions. In next posts, I’d like to share more about the new features of JUnit 5. Recently, I have some posts related to JUnit 5 tutorial. If you’re interested in them, you can refer to following links:

JUnit 5 Tutorial

JUnit 5 with Gradle Example

JUnit 5 Maven Example

JUnit 5 vs JUnit 4

JUnit 5 Basic Introduction

JUnit 5 Annotations Example

JUnit 5 Assertions Example

JUnit 5 Disable or Ignore A Test

JUnit 5 Test Suite – Aggregating Tests In Suites

JUnit 5 Assumptions With Assume

JUnit 5 Nested Tests Examples

Timeout Test in JUnit 5





0 0 vote
Article Rating