I try to implement a data driven test for a kotlin function that has several parameters with default values.
In my test definitions I'd like to be able to leave out any combination of arguments that have a default argument in the function declaration. I don't see how that can work (without a separate branch for each combination of default values).
Maybe it is better explained by code:
import kotlin.test.assertEquals
fun foobalize(start: Int = 0, separator: String = "\t", convert: Boolean = false): Int {
return 0 // implementation omitted
}
data class TestSpec(
val start: Int? = null, // null should mean: Don't pass this argument to foobalize(), but use its default value
val separator: String? = null, // dito
val convert: Boolean? = null, // dito
val expectedResult: Int
)
fun testFoobalize(testSpec: TestSpec) {
// How to call foobalize here with values from TestSpec, but leave out parameters that are null,
// so that the defaults from the fopobalize() function declaration are used???
val actualResult = foobalize(start = testSpec.start)
assertEquals(testSpec.expectedResult, actualResult)
}
Is there some completely different way to do this?
Default parameters is a kotlin compiler feature, so there is no easy way to use it at runtime. It should be possible with reflection though.
IMO if you really want it this way, it's better to enhance the API with another method, which takes a data class as a parameter.
data classc Spec(val start: Int = 0, val separator: String = "\t", val convert: Boolean = false)
fun foobalize(start: Int, separator: String, convert: Boolean): Int {}
fun foobalize(spec: Spec) = foobalize(spec.start, spec.separator, spec.convert)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With