A test method can be marked with @TestFactory annotation in case more test should be invoked but with different input and expected data.
The tests will be organized into Iterable or Collection or Stream. Upon starting the test, JUnit will invoke all tests stored in these objects.
Be aware that @BeforeEach and @AfterEach methods will not be launched before and after, which means the test must contain these codes independently if needed.
Because this test variant changes the tests invoked by JUnit, the variant is called dynamic test.
The return value of the test factory method must be one of these:
Iterable<DynamicTest>
Collection<DynamicTest>
Stream<DynamicTest>
The test input data and their respective expected result should be defined as rows (elements) in a 2D array (matrix) or Collection (e.g. List) or Iterable.
The elements (in the below example entries) should be mapped into a Callable of which the return value has two components:
a String of description of actual test case (e.g. a + b = c with actual input and expected data)
an Assertion with the actual data
EXAMPLE FOR DYNAMIC TESTS (TEST FACTORY, STREAM):
In order to use this variant, dependency must be added to the pom.xml first.
EXAMPLE FOR ADDING DEPENDENCY FOR PARAMETERIZED TESTS:
The parameterized test method must be static and must return a Collection, an Iterator, a Stream or an Array.
The test method will be called for each test case independently (parallel).
Also, @BeforeEach and @AfterEach methods will be launched normally.
As a result, this variant works as a batch for test methods.
The test input data and their respective expected result should be defined as rows (elements) in a 2D array (matrix) or Collection (e.g. List) or Iterable. This must be served by an independent static helper method. The reason is that this method will be called upon all test method invoking.
The test method must be marked with @ParameterizedTest annotation, and with @MethodSource annotation the data serving method should be referenced.
EXAMPLE FOR PARAMETERIZED TEST:
Instead of @MethodSource, other data sources can be used as well.
The @CsvSource annotation defines the number of arguments in the test method signature.
EXAMPLE FOR @CSVSOURCE:
JUnit tries to convert input data to fit to argument types in test method signature. In case custom converter is needed, using the @ConvertWith annotation together with a custom converter class which implements the ArgumentConverter interface (e.g. SimpleArgumentConverter).
EXAMPLE FOR CUSTOM INPUT DATA CONVERTER: