JUnit 5 Dynamic Tests - @TestFactory, DynamicTest With Examples

JUnit @TestFactory annotation coupled with DynamicTest can be used to create a test factory method.

JUnit Dynamic Tests

JUnit @TestFactory methods must not be private or static. These methods must return a Stream, Collection, Iterable, or Iterator of DynamicNode instances.

Any Stream returned by a @TestFactory will be properly closed by calling stream.close(), making it safe to use a resource such as Files.lines() as the initial source of the stream.

DynamicTest is one of the implementation of DynamicNode. Note that dynamic tests are different from @Test cases since callback methods such as @BeforeEach and @AfterEach are not executed for dynamic tests.

JUnit @TestFactory DynamicTest Example

Let’s look at a simple example of using @TestFactory and DynamicTest to create test factory of dynamic tests.

Below image shows the output of the JUnit test execution.


Above example is very simple one, let’s create Dynamic tests for a custom class method. Let’s say we have a utility class defined as:

Here is the test factory method for above function.

Below image shows the execution output of above test method.


Notice that our add method is simple, so in assertEquals() we are using input variables to derive the expected output. If it’s a complex method, we can define a List for expected output and use that in the assertions. We can also define a custom Executable class if we want to have complex testing logic.


JUnit 5 Dynamic tests functionality can be achieved by parameterized tests. Also, Parameterized tests follow the standard JUnit test lifecycle and @BeforeEach and @AfterEach methods are executed for them. Whereas dynamic tests lifecycle is totally different and they don’t have access to @BeforeEach and @AfterEach methods.

You can check out the complete code from our JUnit 5 example project GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: