← Back to Kotlin Course | Chapter 13: Error Handling & Testing | Lesson 4 of 6

JUnit Basics

JUnit is a popular helper toolkit that lets you write small automated checks confirming your Kotlin code behaves the way you expect.

Writing a Basic JUnit Test

A JUnit test is a function annotated with @Test that calls an assertion function, like assertEquals, to check that actual behavior matches an expected value.

Note: Backtick-quoted function names, like ` adding two numbers returns their sum() `, are a common Kotlin convention for descriptive JUnit test names.

Warning: This example uses a third-party testing/mocking library that is not part of the plain Kotlin standard library and must be added as a project dependency (e.g. via Gradle) -- it cannot run in a plain kotlinc sandbox with no dependencies.

Example: Writing a Basic JUnit Test

markup
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals

class CalculatorTest {
    @Test
    fun `adding two numbers returns their sum`() {
        val result = 2 + 3
        assertEquals(5, result)
    }
}

Common Assertions

JUnit provides assertion functions like assertEquals, assertTrue, assertFalse, and assertThrows, each failing the test with a clear message if the expectation is not met.

Warning: This example uses a third-party testing/mocking library that is not part of the plain Kotlin standard library and must be added as a project dependency (e.g. via Gradle) -- it cannot run in a plain kotlinc sandbox with no dependencies.

Example: Common Assertions

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

class ValidationTest {
    @Test
    fun `age validation rejects negative numbers`() {
        assertThrows(IllegalArgumentException::class.java) {
            require(-1 >= 0) { "Age cannot be negative" }
        }
    }
}

Organizing Tests with setUp

A method annotated with @BeforeEach runs before every test in a class, useful for setting up shared fixtures so each test starts from a known, clean state.

Warning: This example uses a third-party testing/mocking library that is not part of the plain Kotlin standard library and must be added as a project dependency (e.g. via Gradle) -- it cannot run in a plain kotlinc sandbox with no dependencies.

Example: Organizing Tests with setUp

markup
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals

class StackTest {
    private lateinit var stack: MutableList<Int>

    @BeforeEach
    fun setUp() {
        stack = mutableListOf()
    }

    @Test
    fun `pushing adds an element`() {
        stack.add(1)
        assertEquals(1, stack.size)
    }
}

Running Tests with Gradle

In a Gradle-based Kotlin project, JUnit tests are executed with ./gradlew test, which compiles the test sources and reports which tests passed or failed.

Example: Running Tests with Gradle

bash
./gradlew test

⚠️ Run this command in your terminal.

Common Mistakes
  1. Forgetting JUnit is a third-party test framework requiring a build tool (Gradle/Maven) dependency; it cannot run from a plain .kt file with kotlinc alone.
  2. Writing test methods that don't start with a clear, descriptive name, making failures harder to understand from the test runner's output alone.
  3. Testing multiple unrelated behaviors in a single test function instead of splitting them into separate, focused tests.
Chapter Summary
  • JUnit is a widely used testing framework for JVM languages, including Kotlin, and requires a Gradle/Maven dependency to use.
  • A test function is marked with @Test and typically uses assertEquals, assertTrue, or similar assertion functions.
  • Test classes and functions are usually placed under a project's src/test/kotlin directory, separate from main source code.
  • Running ./gradlew test executes all JUnit tests in a Gradle-based Kotlin project.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.