Skip to main content
Kotlin Basics
CHAPTER 27 Beginner

Testing in Kotlin

Updated: May 18, 2026
5 min read

# CHAPTER 27

Testing in Kotlin

1. Chapter Introduction

Imagine writing a complex tax calculation function. You test it with a few numbers, and it seems fine. A year later, you add a new feature, accidentally altering the tax logic. Unless you manually re-test every tax scenario, the bug will make it to production. Automated Testing prevents this. In this chapter, we will learn how to write Unit Tests using the JUnit framework to mathematically prove that our Kotlin functions work exactly as intended.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the purpose of Unit Testing.
  • Understand Test-Driven Development (TDD).
  • Use JUnit annotations (@Test).
  • Write assertions (assertEquals, assertTrue).
  • Structure a test using Arrange-Act-Assert.

3. What is Unit Testing?

A Unit Test is a small script that executes a tiny, isolated portion of your code (a "unit", usually a single function) and verifies that the output matches expectations.

If the output matches, the test Passes (Green). If it doesn't match, the test Fails (Red).

4. The Arrange-Act-Assert Pattern

A good test is structured in three phases:
  1. 1. Arrange: Set up the test data (create variables, objects).
  1. 2. Act: Call the actual function you want to test.
  1. 3. Assert: Check if the result is exactly what you expected.

5. Writing a Simple Test (JUnit)

First, let's look at the function we want to test. It lives in our src/main/kotlin folder.
kotlin
12345
class Calculator {
    fun add(a: Int, b: Int): Int {
        return a + b
    }
}

Now, we create a Test Class in our src/test/kotlin folder. We use the @Test annotation to tell JUnit that this is an executable test.

kotlin
12345678910111213141516171819
import org.junit.Assert.assertEquals
import org.junit.Test

class CalculatorTest {

    @Test
    fun testAdditionIsCorrect() {
        // 1. Arrange
        val calc = Calculator()
        val num1 = 5
        val num2 = 10
        
        // 2. Act
        val result = calc.add(num1, num2)
        
        // 3. Assert (Expected Value, Actual Value)
        assertEquals(15, result)
    }
}

When you run this test in IntelliJ, you will get a satisfying Green Checkmark! ✅

6. Common Assertions

JUnit provides several helper functions to check results.
  • assertEquals(expected, actual): Checks if two values are equal.
  • assertNotEquals(unexpected, actual): Checks if they are different.
  • assertTrue(condition): Checks if a boolean is true.
  • assertFalse(condition): Checks if a boolean is false.
  • assertNull(object): Checks if an object is null.

7. Edge Cases

You shouldn't just test the "happy path" (like 5 + 10). You must test Edge Cases! What happens with negative numbers? What happens with zero?
kotlin
123456789
class CalculatorTest {

    @Test
    fun testAdditionWithNegatives() {
        val calc = Calculator()
        val result = calc.add(-5, -5)
        assertEquals(-10, result)
    }
}

8. Test-Driven Development (TDD)

TDD is a professional workflow where you write the test *before* you write the actual code!
  1. 1. Red: Write a test for a feature that doesn't exist yet. Run it. It fails.
  1. 2. Green: Write the bare minimum Kotlin code to make the test pass.
  1. 3. Refactor: Clean up the Kotlin code. The test ensures you didn't break anything!

9. Common Mistakes

  • Testing multiple things in one test: A test should focus on one specific behavior. If a test fails, you should immediately know why based on the test name. Instead of testCalculator(), write testAddition() and testDivisionByZero().
  • Not running tests before committing: The purpose of tests is regression safety. Always run the entire test suite before pushing code to GitHub.

10. Best Practices

  • Descriptive Test Names: Use long, descriptive names for your test functions. Some Kotlin developers even use backticks to allow spaces in test names:
@Test fun \Adding two negative numbers returns correct negative sum\() { ... }

11. Exercises

*(Theoretical)*
  1. 1. We have a function fun isAdult(age: Int): Boolean = age >= 18.
  1. 2. Write a JUnit test using @Test.
  1. 3. Call isAdult(20).
  1. 4. Use assertTrue() to verify the result.

12. MCQs with Answers

Question 1

What is the primary purpose of automated Unit Testing?

Question 2

What is the most popular testing framework used in Kotlin/Java?

Question 3

What annotation must be placed above a function to mark it as an executable test?

Question 4

What does the "Arrange" step in testing mean?

Question 5

Which assertion checks if a specific boolean condition evaluates to true?

Question 6

If val result = 50, what will assertEquals(100, result) do?

Question 7

What does TDD stand for?

Question 8

In TDD, when do you write the test?

Question 9

What is an "Edge Case" in testing?

Question 10

Why is it important to have an automated test suite?

13. Interview Questions

  • Q: Explain the Arrange, Act, Assert pattern in Unit Testing.
  • Q: What is TDD, and what are its benefits? (Answer: TDD forces you to think about the requirements and API design before writing the logic. It also guarantees high test coverage from day one).

14. Summary

Writing code without tests is like building a house on quicksand. While it takes extra time upfront, writing unit tests with JUnit provides an unshakeable safety net. By testing edge cases and utilizing assertions, you can make sweeping changes to your Kotlin architecture a year from now, instantly knowing if you broke anything by simply clicking "Run All Tests."

15. Next Chapter Recommendation

You now possess the technical knowledge of Kotlin. The next step is getting hired. In Chapter 28: Kotlin Interview Preparation, we will review the most frequently asked Kotlin interview questions and coding challenges.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·