0
0
Android Kotlinmobile~5 mins

Unit testing with JUnit in Android Kotlin

Choose your learning style9 modes available
Introduction

Unit testing with JUnit helps check small parts of your code work correctly. It finds mistakes early so your app runs better.

When you write a new function and want to make sure it returns the right result.
When you fix a bug and want to confirm it does not come back.
When you change code and want to check nothing else breaks.
When you want to automate testing so you don't test manually every time.
When you want to share your code with others and prove it works.
Syntax
Android Kotlin
import org.junit.Test
import org.junit.Assert.*

class ExampleUnitTest {
    @Test
    fun testFunction() {
        val expected = 4
        val actual = 2 + 2
        assertEquals(expected, actual)
    }
}

Use @Test annotation to mark a test method.

Use assertions like assertEquals to check expected vs actual results.

Examples
This test checks if 2 + 3 equals 5.
Android Kotlin
import org.junit.Test
import org.junit.Assert.*

class MathTest {
    @Test
    fun addition_isCorrect() {
        assertEquals(5, 2 + 3)
    }
}
This test checks if the string contains the word "Hello".
Android Kotlin
import org.junit.Test
import org.junit.Assert.*

class StringTest {
    @Test
    fun string_containsHello() {
        val text = "Hello World"
        assertTrue(text.contains("Hello"))
    }
}
This test checks that the object is not null.
Android Kotlin
import org.junit.Test
import org.junit.Assert.*

class NullTest {
    @Test
    fun object_isNotNull() {
        val obj: String? = "Kotlin"
        assertNotNull(obj)
    }
}
Sample App

This test class checks the add function of a simple calculator. It tests adding two positive numbers and adding a positive with a negative number.

Android Kotlin
import org.junit.Test
import org.junit.Assert.*

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

class CalculatorTest {
    private val calculator = Calculator()

    @Test
    fun add_twoPositiveNumbers_returnsCorrectSum() {
        val result = calculator.add(3, 7)
        assertEquals(10, result)
    }

    @Test
    fun add_positiveAndNegativeNumber_returnsCorrectSum() {
        val result = calculator.add(5, -2)
        assertEquals(3, result)
    }
}
OutputSuccess
Important Notes

Keep tests small and focused on one thing.

Name test methods clearly to describe what they check.

Run tests often to catch errors early.

Summary

Unit tests check small parts of code work as expected.

JUnit uses @Test and assertions to write tests.

Good tests help find bugs and keep code reliable.