Sling Academy
Home/Kotlin/Testing Class Methods and Properties in Kotlin

Testing Class Methods and Properties in Kotlin

Last updated: December 01, 2024

Testing is an integral part of ensuring software behaves as expected. In Kotlin, testing class methods and properties can be efficiently managed using testing frameworks such as JUnit. This article walks through setting up test cases in Kotlin and explores different ways you can test your classes and their properties.

Setting Up Your Kotlin Project for Testing

To begin with, ensure your Kotlin project is set up with a proper testing framework. JUnit is one of the most popular testing frameworks, and it's well-supported in Kotlin. Add the following dependencies to your build.gradle.kts file to get started:

dependencies {
  testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2")
  testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.2")
}

Creating a Class to Test

Let's assume we have a Kotlin class that we need to test. Consider the following simple data class:

data class Calculator(var history: MutableList = mutableListOf()) {
    fun add(a: Int, b: Int): Int {
        val result = a + b
        history.add("Added $a and $b got $result")
        return result
    }

    fun subtract(a: Int, b: Int): Int {
        val result = a - b
        history.add("Subtracted $b from $a got $result")
        return result
    }
}

Writing Test Cases

With JUnit, you write tests in a class marked with @Test annotations for each test method. Create a new test file, perhaps CalculatorTest.kt to start writing tests:

import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test

internal class CalculatorTest {

    @Test
    fun testAddition() {
        val calculator = Calculator()
        val result = calculator.add(2, 3)
        assertEquals(5, result)
    }

    @Test
    fun testSubtraction() {
        val calculator = Calculator()
        val result = calculator.subtract(5, 2)
        assertEquals(3, result)
    }

    @Test
    fun testHistory() {
        val calculator = Calculator()
        calculator.add(2, 3)
        calculator.subtract(5, 2)
        assertEquals(2, calculator.history.size)
        assertTrue(calculator.history.contains("Added 2 and 3 got 5"))
        assertTrue(calculator.history.contains("Subtracted 2 from 5 got 3"))
    }
}

Running Your Tests

Most IDEs like IntelliJ support directly running JUnit tests. You can also run your tests using Gradle with the following command:

./gradlew test

Gradle will compile your test cases and execute them, showing the results in the command line.

Assertions and Expected Results

JUnit provides a wide range of assertions that you can use to validate the behavior of your methods. Common assertions include:

  • assertEquals(expected, actual) - checks if two values are equal.
  • assertTrue(condition) - checks if a condition is true.
  • assertFalse(condition) - checks if a condition is false.
  • assertNotNull(value) - ensures the value is not null.

Testing Exceptions

In situations where you expect a function to throw an exception, you can use the assertThrows method:

import org.junit.jupiter.api.assertThrows

@Test
fun testZeroDivision() {
    val calculator = Calculator()
    assertThrows {
        // Imagine there's a divide method that throws this exception on invalid input
        calculator.divide(5, 0)
    }
}

Conclusion

Kotlin with JUnit makes it easy to write and run tests against your class methods and properties. A structured approach to testing helps ensure program correctness and improves code quality over time. Mastering testing allows developers to confidently add new features while minimizing the risk of introducing bugs.

Next Article: How to Use Parameterized Tests in Kotlin with JUnit

Previous Article: How to Test Functions in Kotlin with JUnit

Series: Testing in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin