Scrivio Interview library
InternalsIntermediate5 min read · updated 12 November 2026

How do dynamic tests created by a @TestFactory differ from regular tests in terms of lifecycle callbacks?

A @TestFactory method returns a Stream, Collection or Iterable of DynamicTest or DynamicContainer objects, and JUnit runs each one as a test created at runtime. The catch is the lifecycle: @BeforeEach and @AfterEach run once around the factory method, not around each dynamic test, so any per-test setup must be done inside each dynamic test's executable. Dynamic tests suit cases generated from files or data that is only known at runtime.

Why this question is asked

Most tests are written ahead of time, one method per case. Sometimes the cases are only known when the tests run: every JSON file in a folder of examples, every endpoint in an OpenAPI document, every row of a spreadsheet the business maintains. Dynamic tests exist for that, but their lifecycle surprises people, and the surprise causes flaky tests. Interviewers ask about it to see whether we know how JUnit treats these tests internally. In this answer, we will recap regular tests, write a test factory, see exactly when the lifecycle methods run, fix the shared-state bug that follows, and compare dynamic tests with parameterized tests.

1A Quick Recap of Regular Tests

A regular @Test method is discovered when JUnit scans the class, before anything runs. JUnit knows it is a test, gives it a test descriptor, and wraps it in the full lifecycle: a new test instance, extensions, @BeforeEach, the test, @AfterEach. Parameterized tests are similar: each invocation is a full test with its own lifecycle.

2Writing a Test Factory

A @TestFactory method is not a test itself. It is a factory that JUnit calls at runtime; the objects it returns are the tests. Each DynamicTest has a display name and an Executable, the lambda with the test code. A DynamicContainer groups dynamic tests under a name, like a folder.

Java
class InvoiceExamplesTest {
private final InvoiceParser parser = new InvoiceParser();
@TestFactory
Stream<DynamicTest> parsesEveryExampleFile() throws IOException {
Path dir = Path.of("src/test/resources/invoices");
return Files.list(dir) // known only at runtime: 3 files today
.filter(p -> p.toString().endsWith(".json"))
.map(file -> DynamicTest.dynamicTest(
file.getFileName().toString(), // display name
() -> assertNotNull(parser.parse(file)))); // the test itself
}
}
// Report:
// parsesEveryExampleFile()
// basic.json passed
// multi-currency.json passed
// credit-note.json failed

Adding a new example file adds a new test without changing any code. The factory may return a Stream, Collection, Iterable, Iterator or array, and JUnit consumes a Stream lazily and closes it afterwards.

3When the Lifecycle Methods Run

Here is the important difference. JUnit treats the factory method as the thing with a lifecycle. So @BeforeEach runs once, before the factory method is called, and @AfterEach runs once, after all its dynamic tests have finished. Between the dynamic tests nothing runs, and they all share the same test instance. Extensions' BeforeEachCallback and AfterEachCallback follow the same rule, since they are tied to the factory too.

Java
class LifecycleTest {
@BeforeEach void setUp() { System.out.println("beforeEach"); }
@AfterEach void tearDown() { System.out.println("afterEach"); }
@TestFactory Stream<DynamicTest> cases() {
return Stream.of("a", "b", "c")
.map(s -> dynamicTest(s, () -> System.out.println(" test " + s)));
}
}
// beforeEach
// test a
// test b
// test c
// afterEach once, not three times
Step throughLifecycle around a test factory
JUnitTest instanceDynamic tests
@BeforeEach (once)
call @TestFactory method
stream of 3 dynamic tests
run test a
run test b, no @BeforeEach before it
run test c
@AfterEach (once)

7 messages in order. Play them, or step through them one at a time.

4Doing Per-Test Setup Inside Each Dynamic Test

Because there is no @BeforeEach between dynamic tests, any state they change leaks to the next one. Suppose the factory tests a shopping cart and each case adds an item: the second case sees the first case's item, and the results depend on order. The fix is to create fresh state inside each executable.

Java
// Broken: one cart shared by every dynamic test
@TestFactory Stream<DynamicTest> addsItems() {
return Stream.of("book", "pen").map(item -> dynamicTest(item, () -> {
cart.add(item); // cart was created once in @BeforeEach
assertEquals(1, cart.size()); // "pen" fails: size is 2
}));
}
// Fixed: each dynamic test builds its own state
@TestFactory Stream<DynamicTest> addsItemsFixed() {
return Stream.of("book", "pen").map(item -> dynamicTest(item, () -> {
Cart cart = new Cart(); // fresh for this dynamic test
cart.add(item);
assertEquals(1, cart.size()); // passes for both
}));
}

If setup is longer, we put it in a helper method and call it at the start of each executable. Similarly, cleanup goes into a try-finally inside the executable when each test needs it.

5Dynamic Tests Against Parameterized Tests

Both run one piece of logic over many inputs, but they fit different needs. Parameterized tests are better when the cases are fixed and known when we write the test: they get the full lifecycle for each invocation and integrate with all extensions. Dynamic tests are better when the cases come from something only known at runtime, such as files on disk, a schema, or a list from another system, and when we want to build a tree of containers, for example one container per file and one test per field.

Parameterized against dynamic tests
@ParameterizedTest@TestFactory
Cases knownwhen writing the testat runtime
@BeforeEach / @AfterEacharound every invocationonce around the factory
Test instancenew per invocationshared by all dynamic tests
Groupingflat listtree with DynamicContainer

6Follow-up questions

Can a dynamic test be inside a container inside another container?

Yes. DynamicContainer.dynamicContainer(name, children) accepts dynamic tests and other containers, so we can build a tree, for example one container per example file and inside it one test per expected field, and the report shows that tree.

Do dynamic tests show up with useful names in CI?

Yes, each one gets the display name we pass to dynamicTest, so names such as the file name appear in the report. Good names matter even more than usual, because there is no method name to fall back on.

Can a test factory return nothing?

It can return an empty stream, and then no tests run, which is easy to miss if the example folder is empty or the path is wrong. It is a good idea to assert that the source is not empty before building the stream, so a misconfigured path fails loudly.

7Conclusion

In this answer, we saw that a @TestFactory returns a Stream, Collection or Iterable of DynamicTest or DynamicContainer objects created at runtime, which suits cases that come from files or data known only when tests run. The key lifecycle difference is that @BeforeEach and @AfterEach run once around the factory method, not around each dynamic test, and all dynamic tests share one instance, so per-test setup must happen inside each executable.

What to say in the interviewAbout 80 seconds aloud

Open with

A @TestFactory method doesn't contain a test itself. JUnit calls it at runtime and it returns a Stream, Collection or Iterable of DynamicTest or DynamicContainer objects, and each DynamicTest is a display name plus an executable lambda.

Then, if they want more

That's useful when the cases are only known at runtime, for example one test per JSON example file in a folder, or per endpoint in an OpenAPI document; adding a file adds a test without touching code. The important difference from regular and parameterized tests is the lifecycle.

JUnit attaches the lifecycle to the factory method, so @BeforeEach runs once before the factory is called and @AfterEach runs once after all its dynamic tests are done, and the same goes for extension before-each and after-each callbacks. Nothing runs between the dynamic tests, and they all share one test instance.

So if a dynamic test changes state set up in @BeforeEach, the next dynamic test sees it, and results start depending on order. The fix is to do per-test setup inside each executable, like creating a fresh cart at the start of the lambda, or calling a helper method there.

If the cases are fixed and known in advance, I prefer a parameterized test, which gets the full lifecycle per invocation.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JUnit user guide
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do dynamic tests created by a @TestFactory differ from regular tests in terms of...": https://scrivio-interview-library.netlify.app/java/junit/7831e022fc/