Testing / JUnit6 Interview Questions
What are dynamic tests in JUnit 6 and how does @TestFactory work?
Dynamic tests are generated at runtime rather than being declared statically as annotated methods. The @TestFactory method returns a collection or stream of DynamicTest or DynamicContainer objects, each with its own name and executable.
import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import static org.junit.jupiter.api.DynamicTest.dynamicTest; class DynamicTestDemo { // @TestFactory: generates tests at runtime from a Stream @TestFactory Stream<DynamicTest> dynamicTestsFromStream() { return Stream.of("apple", "banana", "cherry") .map(fruit -> dynamicTest( "Is non-empty: " + fruit, () -> assertFalse(fruit.isEmpty()) ) ); } // Generate tests from external data source (database, file) @TestFactory Stream<DynamicTest> testsFromDatabase() { return testDataRepository.findAll().stream() .map(scenario -> dynamicTest( scenario.getName(), () -> { Result result = service.process(scenario.getInput()); assertEquals(scenario.getExpected(), result); } )); } // DynamicContainer: nested dynamic structure @TestFactory Stream<DynamicNode> nestedDynamic() { return Stream.of("cats", "dogs") .map(category -> DynamicContainer.dynamicContainer( "Tests for " + category, Stream.of( dynamicTest("has species", () -> assertNotNull(category)), dynamicTest("is not empty", () -> assertFalse(category.isEmpty())) ) )); } }
More Related questions...