Parameterized tests with JUnit

Parameterized tests with JUnit

Tags
Kotlin
Testing
Published
April 21, 2021
Author
Mateusz Teteruk
Let’s say we have usecase aka interactor which is responsible for doing some calculations. For example computing square of number.
class GetSquareOfNumber { fun execute(number: Int) : Int = number * number }
We want to write unit tests to be sure our logic works as expected. We know input and output of some mocked data. Writing the same copy-pasted test with different data is not the smartest option we have. In this case using parameterized tests is the best solution.
Setup? Fairly easy: – annotate test class with @RunWith(Parameterized::class) – create class representing TestCase and put it in class constructor – create one @Test fun which performs actual test – create static list of test cases annotated with @Parameters(name = „{0}”)name = „{0}” is optional parameter which you can specify. {0} stands for first parameter and in example it is TestCase. Default value in here is just index. In example, TestCase is a data class so in IDE it will print toString() of data class.
Example:
@RunWith(Parameterized::class) class GetSquareOfNumberTest(private val case: TestCase) { private lateinit var getSquareOfNumber: GetSquareOfNumber @Before fun setup() { getSquareOfNumber = GetSquareOfNumber() } @Test fun `compute square of number`() { val result = getSquareOfNumber.execute(case.given) assert(case.expected == result) } companion object { @JvmStatic @Parameters(name = "{0}") fun testCases(): List<TestCase> = listOf( TestCase(1, 1), TestCase(2, 4), TestCase(3, 9), TestCase(4, 16) ) } data class TestCase( val given: Int, val expected: Int ) }
In that way we wrote just single test function and we moved all specification to just list of input data where we can specify input and output (given and expected) values.

Happy coding and remember about testing!