David Kubecka
12/09/2024, 3:52 PMimport org.junit.jupiter.params.provider.Arguments
data class TestData<G, E>(val testName: String, val given: G, val expected: E) {
override fun toString() = testName
}
fun <G, E> List<TestData<G, E>>.asArguments() = map { Arguments.of(it) }
fun myTestMethodTestData() = listOf(
TestData("test case 1", 1, "1"),
TestData("test case 2", 2, "2"),
).asArguments()
This works fine but isn't type-safe, i.e. nothing prevents me from writing
fun myTestMethodTestData() = listOf(
TestData("test case 1", 1, "1"),
TestData("test case 2", "2", 2),
).asArguments()
Is there any way how that can be achieved?
At first I thought I could utilize @NoInfer
to force the user to specify the type arguments explicitly, e.g. asArguments<Int, String>()
, but of course that doesn't enforce anything about the types in the TestData
class instance...Szymon Jeziorski
12/10/2024, 9:55 AMArguments.of
and you later use method myTestMethodTestData
for something like @MethodSource
, you can omit Arguments.of
wrapping and just return List<TestData<G, E>>
in myTestMethodTestData
, it would work the same waySzymon Jeziorski
12/10/2024, 10:04 AMArguments
interface:
data class ExampleTestDataWithMultipleArguments<A : Any, B : Any>(val first: A, val second: B) : Arguments {
override fun get(): Array<Any> = arrayOf(first, second)
}
you could then provide concrete typing for method in `@MethodSource`:
@ParameterizedTest
@MethodSource("someTestDatas")
fun `example test`(first: Int, second: String) {
fun someTestDatas(): List<TestDataWithMultipleArguments<Int, String>> = listOf(
TestDataWithMultipleArguments(1, "1"),
TestDataWithMultipleArguments(2, "2"),
)
David Kubecka
12/10/2024, 12:02 PMyou can omitThanks, I did not know that. That basically makes my original problem useless becausewrapping andArguments.of
TestData
is meant to wrap all data for a single test case so its usage will always be
fun someTestDatas(): List<TestData<Int, String>> = listOf(
TestData(1, "1"),
TestData(2, "2"),
)
Moreover, that explicit return type specification actually provides the type enforcement I was after.