Table of Contents

JUnit 5

Most used annotations

Meta-Annotations / Composed Annotations

Multiple annotations can be composed to one, which can be used later instead.

Example 1

Replace @Tag(“fast”) with @Fast

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag("fast")
public @interface Fast {
}

Usage:

@Fast
@Test
void myFastTest() {
    // ...
}

Example 2

Combine @Tag(“fast”) and @Test to one @FastTest.

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag("fast")
@Test
public @interface FastTest {
}

Usage:

@FastTest
void myFastTest() {
    // ...
}

Assertions

Assumptions

In direct contrast to failed assertions, failed assumptions do not result in a test failure; rather, a failed assumption results in a test being aborted.

Assumptions are typically used whenever it does not make sense to continue execution of a given test method — for example, if the test depends on something that does not exist in the current runtime environment.

Conditional Test Execution

Test Execution Order

@TestMethodOrder(OrderAnnotation.class)
class OrderedTestsDemo {
 
    @Test
    @Order(1)
    void nullValues() {
        // perform assertions against null values
    }
 
    @Test
    @Order(2)
    void emptyValues() {
        // perform assertions against empty values
    }
 
    @Test
    @Order(3)
    void validValues() {
        // perform assertions against valid values
    }
 
}

Test Instance Lifecycle

Parameterized Tests

Repeated Tests

Dynamic Tests

Templates for Test Cases

Misc


JUnit 5 Pros

JUnit 4 -> JUnit 5