JUnit 5 Dynamic Tests - @TestFactory

How to dynamically generate test cases

Dynamic Tests

You can dynamically generate test cases with the @TestFactory annotation. A method annotated with @TestFactory must return a collection of DynamicNode. Strictly speaking, the return value can be a Collection, Iterable, Iterator, Stream, or array.

If a Stream is returned, Jupiter closes it, so streams created by APIs such as Files.lines() can also be used safely.

DynamicNode is an abstract class, so in practice you use either DynamicTest or DynamicContainer. dynamicTest(String, Executable) creates a DynamicTest; the first argument is the test name and the second argument is the test body.

Dynamic Test Lifecycle

@BeforeEach and @AfterEach run before and after the method annotated with @TestFactory; they do not run before and after each individual dynamic test.

Creating Nested Dynamic Tests

Use DynamicContainer to create nested dynamic tests. A container can include dynamic tests and other dynamic containers, allowing hierarchical test output.