Testing Using Kotlin
Testing Using Kotlin
Testing
The software development experience we’ve accumulated over the many years
unfortunately tells us that
● If a program does not contain bugs, the algorithm that it implements contains
them.
● If neither the program nor the algorithm contains bugs, no one needs the
program (almost always).
Testing
Ariane 5
Testing: history
● Late 70s: Show that the program does not work correctly.
● Testing demonstrates the presence of defects, but it does not prove their absence.
● Many more.
Testing: types
● Load – Simulating a real load (for example, a certain number of users on the
server).
Testing: types
● Regression – Making sure new changes did not break anything that had
worked previously.
Testing: types
● Regression – Making sure new changes did not break anything that had
worked previously.
For each non-trivial function, their own tests are written that check that the
method works correctly:
● Frequent launch expected ⇒ should run fast
The JUnit5 framework is the most popular way to test Java and Kotlin programs.
dependencies {
...
testImplementation(platform("org.junit:junit-bom:5.8.2"))
testImplementation("org.junit.jupiter:junit-jupiter:5.8.2")
}
tasks.test {
useJUnitPlatform()
}
class MyTests {
@Test
@DisplayName("Check if the calculator works correctly")
fun testCalculator() {
Assertions.assertEquals(
3,
myCalculator(1, 2, "+"),
"Assertion error message"
)
}
}
Unit testing in Kotlin
class MyParametrizedTests {
companion object {
@JvmStatic
fun calculatorInputs() = listOf(
Arguments.of(1, 2, "+", 3),
Arguments.of(0, 5, "+", 5),
)
}
@ParameterizedTest
@MethodSource("calculatorInputs")
fun testCalculator(a: Int, b: Int, op: String, expected: Int) {
Assertions.assertEquals(expected, myCalculator(a, b, op), "Assertion error message")
}
}
Unit testing in Kotlin
● @BeforeEach – Methods with this annotation are run before each test.
● @AfterEach – Methods with this annotation are run after each test.
● @BeforeAll – Methods with this annotation are run before all tests in the class.
● @AfterAll – Methods with this annotation are run after all tests in the class.
Code quality
Often, testing includes checking not only the correctness of the functionality but also the
quality of the code itself.
Static code analyzers such as detekt, ktlint, and diktat exist to help you avoid having to do
this manually.