1. Introduction

This article is going to cover about tagging and filtering in JUnit 5, a feature that allows test classes and methods can be tagged. And those tags can later be used to filter test discovery and execution.

The tagging feature in JUnit 5 is very similar to the Categories feature in JUnit 4. In other words, this feature of JUnit 5 is intended to replace the  Categories feature of JUnit 4. We can use the tagging feature to group and label related test classes or methods together, and we can exclude or include the tests in our build process by using those tagged labels.

2. JUnit 5 Tagging and Filtering Example

2.1. Prerequisite

  • A sample Java project with JUnit 5 enabled
  • Maven or Gradle installed

You can refer to  Getting started with JUnit 5 to get those thing ready on your machine.

2.2. Tagging a class or a test method

In JUnit 5, to tag a class or a test method, we annotate it with @Tag annotation. Let’s see an example below:

2.3. Filtering tests

We can filter the tagged tests by configuring the filters extension. Here is an example how we configure the JUnit 5 Gradle plugin in order to include all the tests tagged with “service” , “fast” and exclude the tests tagged by “slow“.

And here is an example how we configure the JUnit 5 Maven surefire provider to include all the tests tagged with “service” , “slow” and exclude the tests tagged by “fast“.

3. Conclusion

In this article, we have just learned about the tagging and filtering in JUnit 5, which allow us group the tests together and plan for their executions for different purposes with the filter extension. We can see several applications of this feature such as: splitting the tests according to their execution speeds (fast, slow), splitting the tests according to environment (plain Unit tests, integration tests, etc).

The sample code can be found in the Github project or you can download it by access this link: junit5-samples.zip

Below are other related article for your references:

JUnit 5 Tutorial

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 Dynamic Tests – Generate Tests at Run-time

JUnit 5 Nested Tests Examples

JUnit 5 Test Suite – Aggregating Tests In Suites

JUnit 5 Maven Example

JUnit 5 with Gradle Example

JUnit 5 Parameter Resolution Example

 

0 0 vote
Article Rating