0
0
Kotlinprogramming~5 mins

Why testing matters in Kotlin

Choose your learning style9 modes available
Introduction

Testing helps find mistakes in your code early. It makes sure your program works as expected and keeps it reliable.

When you want to check if a new feature works correctly before sharing it.
When you fix a bug and want to make sure it is really fixed.
When you change code and want to be sure nothing else breaks.
When you want to make your program safe to use by others.
When you want to save time by catching errors early instead of later.
Syntax
Kotlin
fun testFunction() {
    // Write code to check if your function works
    val result = yourFunction()
    assert(result == expectedValue) { "Test failed!" }
}

Use assert to check if a condition is true.

If the condition is false, the program shows the message inside the curly braces.

Examples
This test checks if adding 2 and 3 gives 5.
Kotlin
fun testSum() {
    val sum = 2 + 3
    assert(sum == 5) { "Sum should be 5" }
}
This test checks if the greeting message is correct.
Kotlin
fun testGreeting() {
    val greeting = "Hello" + " World"
    assert(greeting == "Hello World") { "Greeting is wrong" }
}
Sample Program

This program defines a simple add function and tests it. If the test passes, it prints "Test passed!".

Kotlin
fun add(a: Int, b: Int): Int {
    return a + b
}

fun testAdd() {
    val result = add(4, 5)
    assert(result == 9) { "Test failed: 4 + 5 should be 9" }
    println("Test passed!")
}

fun main() {
    testAdd()
}
OutputSuccess
Important Notes

Testing early helps catch errors before they cause bigger problems.

Good tests make your code easier to change and improve safely.

Write simple tests that check one thing at a time.

Summary

Testing finds mistakes and keeps your program working well.

Use tests to check your code often, especially after changes.

Simple tests help you trust your code and save time fixing bugs.