0
0
Kotlinprogramming~5 mins

Kotlin test assertions

Choose your learning style9 modes available
Introduction

Test assertions help you check if your code works as expected by comparing actual results with what you want.

When you want to check if a function returns the correct value.
When you want to verify that a variable has the expected content.
When you want to make sure an error or exception happens as planned.
When you want to confirm that two objects are equal or not equal.
When you want to test if a condition is true or false during your program.
Syntax
Kotlin
assertEquals(expected, actual)
assertTrue(condition)
assertFalse(condition)
assertNotNull(value)
assertNull(value)
assertFailsWith<ExceptionType> { code }

These functions come from Kotlin's test libraries like kotlin.test or JUnit.

You usually write these inside test functions to check your code automatically.

Examples
Check if the sum of 2 and 3 equals 5.
Kotlin
assertEquals(5, sum(2, 3))
Check if the variable isValid is true.
Kotlin
assertTrue(isValid)
Check if calling parseNumber with "abc" throws an IllegalArgumentException.
Kotlin
assertFailsWith<IllegalArgumentException> {
    parseNumber("abc")
}
Sample Program

This program tests the add function with different assertions. It also checks that converting "abc" to an integer throws a NumberFormatException.

Kotlin
import kotlin.test.*

fun add(a: Int, b: Int): Int = a + b

fun main() {
    assertEquals(7, add(3, 4))
    assertTrue(add(1, 1) == 2)
    assertFalse(add(2, 2) == 5)
    assertNotNull(add(0, 0))
    assertNull(null)

    val exception = assertFailsWith<NumberFormatException> {
        "abc".toInt()
    }
    println("Caught exception: ${exception.message}")
}
OutputSuccess
Important Notes

Use clear messages in assertions to understand failures better.

Assertions help catch bugs early by testing small parts of your code.

Run tests often to keep your code reliable.

Summary

Assertions check if your code behaves as expected.

Use different assertions for equality, truth, null checks, and exceptions.

Write assertions inside test functions to automate checking your code.