`TestFactory` Annotation
Learn to write dynamic tests in JUnit 5 using the @TestFactory annotation.
We'll cover the following
JUnit 5 provides the @Test
annotation in the Jupiter module to write standard unit tests. These test cases assume the behavior of the test. It’s not possible to change the behavior of the tests if anything happens at runtime.
Assumptions provide a basic form of dynamic behavior but are rather limited in their expressiveness.
Jupiter introduced a new dynamic model that generates tests at runtime. These tests are called dynamic tests. They are generated at runtime by a factory method annotated with the @TestFactory
annotation.
Note: The factory method with the
@TestFactory
annotation is not a regular test. It’s a general factory method that generates the test case.
A dynamic
test is composed of a display name
and an executable
.
An executable is a @FunctionalInterface
introduced in Java 8
. This means that the implementations are provided either as a lambda expression or as a method reference.
Rules for writing @TestFactory
methods
A method that is annotated with the @TestFactory
annotation must return one of the following:
- A single
DynamicNode
object - A
stream
ofDynamicNode
objects - A
collection
ofDynamicNode
objects - An
iterable
ofDynamicNode
objects - An
iterator
ofDynamicNode
objects - An array of
DynamicNode
objects
Similar to tests annotated with @Test
annotation, factory methods annotated with @TestFactory
must not be private
or static
. They are allowed to have the access modifier as package-private.
Code example
Get hands-on with 1400+ tech skills courses.