More flexibility somehow means it is more complex and boilerplate to write especially most of the time the test case is rather static but not so dynamic.
Consider I want to test Math.add()
:
The parameterized test version looks likes :
@ParameterizedTest
@CsvSource({ "1,1,2",
"2,2,4",
"3,3,6",
"4,4,8",
"5,5,10",
"6,6,12",
"7,7,14",
"10,90,100" })
public void parameterizedTest(int left, int right, int expected) {
assertEquals(expected, Math.addExact(left, right));
}
The dynamic test version looks likes:
@TestFactory
Collection<DynamicTest> dynamicTest() {
return Arrays.asList(
DynamicTest.dynamicTest("Test1", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Test2", () -> assertEquals(4, Math.addExact(2, 2))),
DynamicTest.dynamicTest("Test3", () -> assertEquals(6, Math.addExact(3, 3))),
DynamicTest.dynamicTest("Test4", () -> assertEquals(8, Math.addExact(4, 4))),
DynamicTest.dynamicTest("Test5", () -> assertEquals(10, Math.addExact(5, 5))),
DynamicTest.dynamicTest("Test6", () -> assertEquals(12, Math.addExact(6, 6))),
DynamicTest.dynamicTest("Test7", () -> assertEquals(14, Math.addExact(7, 7))),
DynamicTest.dynamicTest("Test8", () -> assertEquals(100, Math.addExact(10, 90))));
}
It already has many boilerplate codes.So I try to use return Stream<DynamicTest>
to remove these boilerplate codes :
@TestFactory
Stream<DynamicTest> dynamicTest2() {
return Stream.of(
"1,1,2",
"2,2,4",
"3,3,6",
"4,4,8" ,
"5,5,10" ,
"6,6,12" ,
"7,7,14",
"10,90,100")
//How to do????????
.map(data-> DynamicTest.dynamicTest(data, () -> assertEquals(xxx, Math.addExact(yy,zz))));
}
But how can I convert my test data which is in the string format to the arguments and call the SUT. I look around DynamicTest
API to see if there are anything can help me but can't find anything helpful, so I give up .....
So ,I would prefer parametrised test. More elegant ,clean, easy to read and write. Readability of the test case is more important.