To continue the series about JUnit 5 tutorial, we will get to know about JUnit 5 Assumptions. During the development, there are some situations that the source code is not written well, dependent on some conditions temporarily and this might cause several tests to fail. For example, a Backup file function should work on any operating systems but currently, it can work only on Windows. To allow the developer to run tests the source code like the above function, JUnit 5 provides us its assumptions feature.

1. Preparation

You need to get JUnit 5 setup on your environment. Below are some options for your references:

The sample code presented in this tutorial is available on my Github project. It’s a both Maven and Gradle projects, so it’s easy to run or imported into any IDE.

2. JUnit 5 Assumptions

Let’s assume we have a class which is responsible for scheduling meetings and backup the calendar to file system.

At the time of writing this class, the doSchedule can work with the US/Moutain timezone and US locale while it should work with any locale and timezone. And the backupCalendar method can work with Windows file system while it should work on any operating system.

We will try to write some tests using JUnit 5 assumption features as below.

We will write tests for the method doSchedule first.

2.1.  Using packages of JUnit 5

2.2. Assume the current timezone is US/Mountain

Note that if the assumption is false, then all the tests under the assumeTrue command, will be skipped.

2.3. Assume the current locale is the US

The next section, we will try to test the backupCalendar method.

2.4. Assume the current OS is Windows

3. Output of Example

Here is the output on my Eclipse:

JUnit 5 Assumptions

JUnit 5 Assumptions – Output

Because my OS is Windows, timezone is not US/Mountain, and locale is the US, the test “doScheduleSingleTimeZone” was skipped.

4. Conclusions

We have learned about JUnit 5 assumptions with several basic examples. Note that beside assumeTrue annotation, JUnit 5 provide use more assumption commands like assumeTrue, assumeThat, etc. Besides, those commands can be used with Java 8 Lambda Expression. In next posts, I’d like to share more about JUnit 5 features like Tag, Filter, etc. Recently, I have some posts related to JUnit 5. If you’re interested in, you can refer to the following links:

JUnit 5 Tutorial

JUnit 5 Basic Introduction

JUnit 5 vs JUnit 4

JUnit 5 Annotations Example

JUnit 5 Assertions Example

JUnit 5 Disable or Ignore A Test

JUnit 5 Exception Testing

JUnit 5 Test Suite – Aggregating Tests In Suites

JUnit 5 Dynamic Tests – Generate Tests at Run-time

JUnit 5 Nested Tests Examples

JUnit 5 Maven Example

JUnit 5 with Gradle Example

Timeout Test in JUnit 5

0 0 vote
Article Rating