https://kotlinlang.org logo
#feed
Title
# feed
j

Jarosław Michalik

08/11/2020, 7:16 AM
s

Stephan Schroeder

08/11/2020, 8:47 AM
interesting topic! this is how I use JUnit Parameterized tests in Kotlin. TLDR: because JUnit only(?) knows static methods for data providers, you have to put them in a companion object and annotate them with
@Static
Example:
Copy code
class ProductPredicateTest {
    private val product: Product = mockk()

    @BeforeEach
    fun setup() {
        clearMocks(product)
    }

    @ParameterizedTest
    @MethodSource("getOrPredicateProvider")
    fun `getOrPredicate should return an at-least-one-combination of all the predicates`(
            alwaysOrNeverTruePredicates: List<Boolean>,
            expectedOrCombinationResult: Boolean
    ) {
        val orPredicate: ProductPredicate = getOrPredicate(
                alwaysOrNeverTruePredicates.map { if(it) alwaysTruePredicate else neverTruePredicate }
        )
        assertThat(orPredicate(product)).isEqualTo(expectedOrCombinationResult)
    }

    companion object {
        @JvmStatic
        private fun getOrPredicateProvider(): List<Arguments?> = listOf(
            Arguments.of(
                listOf(false, false, false),
                false),
            Arguments.of(
                listOf(false, true, false),
                true),
            Arguments.of(
                listOf(true, true, true),
                true)
            )
    }
}
c

cedric

08/12/2020, 3:34 AM
For what it's worth, TestNG has supported parameterized testing since 2004 and without requiring any of them being static 🙂
s

Stephan Schroeder

08/12/2020, 7:08 AM
yeah, that's why I prefer TestNG as well! But since JUnit5 came out the corporate choice (at least where I work) swung back to JUnit for some reason. At least I can now have multiple parameterized tests in the same class.
44 Views