Testing / JUnit6 Interview Questions
What are dynamic tests in JUnit 6 and how do you create them with @TestFactory?
Dynamic tests are tests generated at runtime rather than defined at compile time. They are created using @TestFactory methods that return a Stream, Collection, or Iterable of DynamicTest objects.
import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import static org.junit.jupiter.api.DynamicTest.dynamicTest; class DynamicTestsDemo { // Basic: generate tests from a list at runtime @TestFactory Stream<DynamicTest> dynamicAdditionTests() { return Stream.of( dynamicTest("1 + 1 = 2", () -> assertEquals(2, 1 + 1)), dynamicTest("5 + 3 = 8", () -> assertEquals(8, 5 + 3)), dynamicTest("-1 + 1 = 0", () -> assertEquals(0, -1 + 1)) ); } // Useful: load test data from a file, database, or API at runtime @TestFactory Stream<DynamicTest> testsFromDatabase() { return testDataRepository.findAll().stream() .map(data -> dynamicTest( "Validate: " + data.id(), () -> { Result result = service.process(data); assertEquals(data.expectedStatus(), result.status()); assertNotNull(result.processedAt()); } )); } // Dynamic node containers (hierarchical dynamic tests) @TestFactory Stream<DynamicNode> hierarchical() { return Stream.of( dynamicContainer("Positive numbers", Stream.of( dynamicTest("1 is positive", () -> assertTrue(1 > 0)), dynamicTest("100 is positive", () -> assertTrue(100 > 0)) ) ) ); } }
Key distinction: @ParameterizedTest tests are registered at discovery time (the count is known before execution). Dynamic tests are created at runtime -- the count may not be known until the @TestFactory method is called.
More Related questions...