Introduction
JUnit is a framework in Java used for unit testing. It is vital in the development of test-driven development. It is part of the xUnit frameworks. We link the JUnit as a JAR file at compile time. JUnit5 resides under the org.junit.jupiter package in Java.
import org.junit.jupiter.api.*;A Dynamic Test is one of the most commonly used tests, and it is generated at the run time. We use the TestFactory method to generate Dynamic Tests in JUnit5. TestFactory method is a non-static and non-private method having a return type as Stream, Collection, Iterator, Iterable, or an array of Dynamic Tests. Providing any other return type to TestFactory will result in an error.
Basic Syntax
Let us look at an example of Dynamic Tests in this section to understand the Syntax,
@TestFactory
Stream<DynamicTest> dynamicTestStream() {
return IntStream.of(0, 2, 4, 6)
.mapToObj(v ->
dynamicTest(v + " is a multiple of 2",()->assertEquals(0,v%2))
);
}In the above code, first, we invoke the TestFactory method so that the compiler can recognize it as a test factory containing multiple Dynamic Tests.
We have selected the method's return type as a stream of Dynamic Tests. We then test whether the stream of numbers is divisible by two or not.
As discussed earlier, many more options are available for choosing the return type.
@TestFactory
//Dynamic Test with return type as Iterable
Iterable<DynamicTest> dynamicTestsWithIterable() {
return Arrays.asList(
DynamicTest.dynamicTest("Add test",
() -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test",
() -> assertEquals(4, Math.multiplyExact(2, 2))));
}
@TestFactory
//Dynamic Test with return type as Iterator
Iterator<DynamicTest> dynamicTestsWithIterator() {
return Arrays.asList(
DynamicTest.dynamicTest("Add test",
() -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test",
() -> assertEquals(4, Math.multiplyExact(2, 2))))
.iterator();
}
@TestFactory
//Dynamic test with return type as collection of Dynamic Test
Collection<DynamicTest> dynamicTestsWithCollection() {
return Arrays.asList(
DynamicTest.dynamicTest("Add test",
() -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test",
() -> assertEquals(4, Math.multiplyExact(2, 2))));
}Check out JUnit Interview Questions here.




