To continue the series about JUnit 5 tutorials, in this post, we will try to get to know about JUnit 5 test suite which is a concept of aggregating multiple test classes in a test suite so that we can run those together.
1. Preparation
You will need to get JUnit 5 be ready in your environment. You can prepare by yourselves or refer to my recently post to get JUnit 5 set up Eclipse, Maven or Gradle.
2. JUnit 5 Test Suite
JUnit 5 provides us 2 annotations: @SelectPackages and @SelectClasses to create test suites.
Assume that we will have 3 packages and their test classes as below:
- Package xyz.howtoprogram.junit5.order
TestOrderService.java
- Package xyz.howtoprogram.junit5.payment
TestPaymentService.java
- Package xyz.howtoprogram.junit5.user
TestPasswordService.java
TestUserService.java
We will aggregate those classes in different suites.
2.1. JUnit 5 Test Suite with @SelectPackages.
@SelectPackage is used to specify the names of packages to be selected when running a test suite.
For example, we will create a suite which contains all test classes in the package: xyz.howtoprogram.junit5.user
1 2 3 4 5 6 7 8 |
import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.runner.SelectPackages; import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) @SelectPackages("xyz.howtoprogram.junit5.user") public class UserFeatureSuite { } |
When we run this suite, the test runner will run all the test classes in this package and its child packages.
Here is example on my Eclipse.
2.1. JUnit 5 Test Suite with @SelectClasses.
@SelectClasses is used to specify the classes to be selected when running a test suite. For example, below class will create a suite contains test classes on different packages: TestUserService.class, TestOrderService.class, TestPaymentService.class
1 2 3 4 5 6 7 8 |
import xyz.howtoprogram.junit5.order.TestOrderService; import xyz.howtoprogram.junit5.payment.TestPaymentService; import xyz.howtoprogram.junit5.user.TestUserService; @RunWith(JUnitPlatform.class) @SelectClasses({TestUserService.class, TestOrderService.class, TestPaymentService.class}) public class PlayOrderFeatureSuite { } |
When we run this suite, the test runner will run all those test classes. Below is an example on my Eclipse:
3. Conclusions.
We have learned about JUnit 5 test suite by using @SelectPackage and @SelectClasses to aggregate test classes into test suite. In next post, I’d like to share about aggregate test by using Tag and Filter which are new concepts introduced in JUnit 5. Recently, I have some posts related to JUnit 5 tutorial. If you’re interested in them, you can refer to the following links:
JUnit 5 Disable or Ignore A Test
JUnit 5 Dynamic Tests – Generate Tests at Run-time
JUnit 5 Assumptions With Assume