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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
