In this article, we will walk through some JUnit 5 annotations that often be used when we write tests.

1. Preparation

This section introduces some preparations you may need to set up if you want to get started with JUnit 5.

2. JUnit 5 Annotations

Below are some basic JUnit 5 annotations that we often use when we write tests.

JUnit 5 Annotations Descriptions
@BeforeEach The annotated method will be run before each test method(annotated with @Test) in the current class.
@AfterEach The annotated method will be run after each test method (annotated with @Test) in the current class.
@BeforeAll The annotated method will be run before all test methods in the current class.
@AfterAll The annotated method will be run after all test methods in the current class.
@Test Declares a test method
@DisplayName Define custom display name for a test class or test method
@Disable Is used to disable or ignore a test class or method.
@Nested Used to declare nested test classes
@Tag Declare tags for test discovering and filtering
@TestFactory Denotes a method is a test factory for dynamic tests in JUnit 5

Below is an example of test class written by using JUnit 5 annotations

Let’s see the console output when we run the test.

Note that the testMethod2 was disabled. So, it was not run.

Here is the test result when I run on my IntelliJ

JUnit 5 Annotations Example

JUnit 5 Annotations Example

3. Summary

We have seen some JUnit 5 annotations which are very basic and almost standard test classes often have. Note that if you’re familiar with the JUnit 4, you can see that all those annotations are different with the ones of JUnit 4. If you want to get to know the differences between JUnit 5 and JUnit 4 and other features of JUnit 5 as well, you can refer to my recent posts:

JUnit 5 Tutorial

Introduction To JUnit 5 – The Next Generation of JUnit

JUnit 5 vs JUnit 4

JUnit 5 Assertions Example

JUnit 5 and Spring Boot 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 Assumptions With Assume

JUnit 5 Parameter Resolution Example

Timeout Test in JUnit 5

 

 

 

0 0 vote
Article Rating