Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Testing

Kotlin Testing

Testing is the first line of defense for code correctness; it lets you quickly confirm that changes haven't broken existing functionality.

Kotlin provides the cross-platform testing library kotlin.test, which together with JUnit lets you write concise, readable unit tests.


kotlin.test and JUnit

These two names often appear together, but their responsibilities differ.

JUnit is the most mainstream testing framework on the JVM, responsible for discovering test methods, organizing the execution flow, and generating test reports.

kotlin.test is the official Kotlin testing library; it defines a unified set of assertion APIs and annotations.

kotlin.test is not itself a framework; it forwards assertions to the underlying test framework via adapters, defaulting to JUnit on the JVM.

Test code written this way can be reused cross-platform; just swap the adapter on Kotlin/JS or Kotlin/Native.

Component Responsibility Typical contents
JUnit 5 Testing framework, responsible for running and reporting Discovery of @Test, test lifecycle, report generation
kotlin.test Unified assertion and annotation API assertEquals、assertTrue、assertFailsWith
kotlinx-coroutines-test Coroutine testing support runTest, virtual time, TestDispatcher

Tip:JUnit 4 and JUnit 5 differ in both package names and annotations. New projects should use JUnit 5 directly; its extension model is more flexible, and Gradle requires explicitly declaring useJUnitPlatform().


Adding dependencies

In a Gradle project, test dependencies go in the testImplementation configuration and are visible only to the test source set.

kotlin("test") automatically selects the adapter version matching the current testing framework.

Example

// File path: build.gradle.kts

plugins

{

    kotlin

(

"jvm"

)

version

"2.2.0"

}

repositories

{

    mavenCentral

(

)

}

dependencies

{

   

// kotlin.test unified assertion API; version is determined automatically by the Kotlin plugin

    testImplementation

(

kotlin

(

"test"

)

)

   

// JUnit 5 aggregate package, including the API and runtime engine

    testImplementation

(

"org.junit.jupiter:junit-jupiter:5.11.4"

)

}

tasks.

test

{

   

// Since Kotlin 1.5, using JUnit 5 requires explicitly declaring the test platform

    useJUnitPlatform

(

)

}

Test sources go under the src/test/kotlin directory, with package names consistent with the main code.

Below is the business code under test; the file path is src/main/kotlin/com/runoob/Calculator.kt.

Example

// File path: src/main/kotlin/com/runoob/Calculator.kt

package

com.runoob

class

Calculator

{

   

// Add two numbers

    fun add

(

a

:

Int, b

:

Int

)

:

Int

=

a

b

   

// Divide two numbers; throw an exception when the divisor is 0

    fun divide

(

a

:

Int, b

:

Int

)

:

Int

{

        require

(

b

!=

0

)

{

"Divisor cannot be 0"

}

       

return

a

/

b

   

}

}


The first test

A test class is usually named after the class under test with a Test suffix, and test methods are marked with the @Test annotation.

It is recommended that method names directly describe the behavior being tested, so a failing test report is easy to understand at a glance.

Example

// File path: src/test/kotlin/com/runoob/CalculatorTest.kt

package

com.runoob

import

kotlin.test.Test

import

kotlin.test.assertEquals

import

kotlin.test.assertFailsWith

import

kotlin.test.assertTrue

class

CalculatorTest

{

   

// This instance is recreated before each test method runs

   

private

val calculator

=

Calculator

(

)

    @Test

    fun addReturnsSumOfTwoNumbers

(

)

{

       

// assertEquals(expected value, actual value)

        assertEquals

(

5

, calculator.

add

(

2

,

3

)

)

        assertEquals

(

0

, calculator.

add

(

1

,

1

)

)

   

}

    @Test

    fun divideByZeroThrowsException

(

)

{

       

// assertFailsWith asserts that a code block throws the specified exception and returns that exception object

        val error

=

assertFailsWith

<

IllegalArgumentException

{

            calculator.

divide

(

10

,

0

)

       

}

        assertEquals

(

"Divisor cannot be 0"

, error.

message

)

   

}

    @Test

    fun divideReturnsPositiveResult

(

)

{

        assertTrue

(

calculator.

divide

(

10

,

2

)

0

)

   

}

}

After running gradlew test, all three tests pass.



$ ./gradlew test



> Task :test

BUILD SUCCESSFUL in 2s



3 tests completed

If an assertion fails, the report shows a comparison of the expected and actual values, making it very direct to locate the problem.



$ ./gradlew test



> Task :test FAILED



CalculatorTest > addReturnsSumOfTwoNumbers FAILED

    java.lang.AssertionError at CalculatorTest.kt:16

        expected: 6 but was: 5



BUILD FAILED in 2s


Assertion function table

kotlin.test provides a set of clearly named assertion functions covering the vast majority of testing scenarios.

When an assertion fails, an AssertionError is thrown, and Gradle aggregates the failure information into the test report.

Assertion functions Purpose Example
assertEquals Assert that two values are structurally equal assertEquals(4, calculator.add(2, 2))
assertNotEquals Assert that two values are not equal assertNotEquals(5, calculator.add(2, 2))
assertTrue Assert that a condition is true assertTrue(list.isEmpty())
assertFalse Assert that a condition is false assertFalse(list.isNotEmpty())
assertNull Assert that a value is null assertNull(map["missing"])
assertNotNull Assert that a value is not null assertNotNull(result)
assertSame Assert that two references point to the same object assertSame(a, b)
assertNotSame Assert that two references point to different objects assertNotSame(a, b)
assertFailsWith Assert that a specified exception is thrown and return that exception assertFailsWith { ... }
assertContains Assert that a collection or range contains a certain element assertContains(listOf(1, 2, 3), 2)

assertEquals also has an overload with a message parameter that outputs a custom hint when the assertion fails.

Example

// The third parameter is the message shown on failure, making debugging easier

assertEquals

(

5

, calculator.

add

(

2

,

3

)

,

"2 + 3 should equal 5"

)


Test Lifecycle

Multiple test methods often need to share the same setup and cleanup logic, such as establishing a database connection or creating temporary files.

kotlin.test provides four lifecycle annotations, each executed once before or after every test method.

Annotation Execution Timing Typical use
@BeforeTest Before each test method runs Create objects, prepare test data
@AfterTest After each test method runs Close resources, clean up temporary files
@BeforeAll Before all test methods in the class, executed only once Expensive operations such as starting a server
@AfterAll After all test methods in the class, executed only once Global cleanup such as shutting down the server

@BeforeAll and @AfterAll come from JUnit 5; in Kotlin they must be written in a companion object with @JvmStatic, otherwise the framework cannot find them.

Example

// File path: src/test/kotlin/com/runoob/SiteTest.kt

package

com.runoob

import

kotlin.test.AfterTest

import

kotlin.test.BeforeTest

import

kotlin.test.Test

import

kotlin.test.assertEquals

class

SiteTest

{

   

// Test data container, rebuilt before each test method runs

   

private

lateinit var sites

:

MutableList

<

String

@BeforeTest

    fun setUp

(

)

{

       

// Each test method starts with clean data to avoid tests affecting each other

        sites

=

mutableListOf

(

"Runoob"

,

"RUNOOB"

)

   

}

    @AfterTest

    fun tearDown

(

)

{

       

// Clean up data, release memory

        sites.

clear

(

)

   

}

    @Test

    fun addSiteIncreasesSize

(

)

{

        sites.

add

(

"www.runoob.com"

)

        assertEquals

(

3

, sites.

size

)

   

}

    @Test

    fun sitesStartWithTwoElements

(

)

{

       

// Because setUp runs for every method, this is always 2

        assertEquals

(

2

, sites.

size

)

   

}

}

On the JVM, kotlin.test annotations map to corresponding JUnit 5 annotations: @BeforeTest is equivalent to @BeforeEach, and @AfterTest is equivalent to @AfterEach.

Note:Do not do particularly time-consuming work in @BeforeTest, because it runs once for every test method. If you really need to, use @BeforeClass instead so it runs only once.


Parameterized Tests

When the same logic needs to be verified with multiple sets of data, copying multiple test methods is both verbose and hard to maintain.

Parameterized tests extract data into a table, and the framework automatically generates a separate test case for each row of data.

kotlin.test itself does not provide parameterized annotations; on the JVM you can just use JUnit 5's @ParameterizedTest.

Example

// File path: src/test/kotlin/com/runoob/CalculatorParameterizedTest.kt

package

com.runoob

import

org.junit.jupiter.params.ParameterizedTest

import

org.junit.jupiter.params.provider.CsvSource

import

kotlin.test.assertEquals

class

CalculatorParameterizedTest

{

   

private

val calculator

=

Calculator

(

)

   

// Each row of CSV data runs the test method once

    @ParameterizedTest

(

name

=

"{0} + {1} = {2}"

)

    @CsvSource

(

       

"1, 2, 3"

,

       

"0, 0, 0"

,

       

"-1, 1, 0"

,

       

"100, 200, 300"

   

)

    fun addReturnsExpectedSum

(

a

:

Int, b

:

Int, expected

:

Int

)

{

        assertEquals

(

expected, calculator.

add

(

a, b

)

)

   

}

}

After running, the report shows four separate cases, and if any one fails you can immediately tell which set of data caused the problem.



$ ./gradlew test



> Task :test

CalculatorParameterizedTest > 1 + 2 = 3 PASSED

CalculatorParameterizedTest > 0 + 0 = 0 PASSED

CalculatorParameterizedTest > -1 + 1 = 0 PASSED

CalculatorParameterizedTest > 100 + 200 = 300 PASSED



BUILD SUCCESSFUL in 2s


Coroutine testing

Suspending functions cannot be called directly in a regular test method; you need to wrap them with runTest.

runTest comes from kotlinx-coroutines-test, which creates a test dispatcher with virtual time.

The delay in the code is skipped immediately, so the test does not need to really wait one second and runs very fast.

Example

// File path: build.gradle.kts

dependencies

{

    implementation

(

"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2"

)

    testImplementation

(

kotlin

(

"test"

)

)

   

// Coroutine test library, providing runTest and the test dispatcher

    testImplementation

(

"org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2"

)

}

Example

// File path: src/test/kotlin/com/runoob/GreetTest.kt

package

com.runoob

import

kotlinx.coroutines.delay

import

kotlinx.coroutines.test.runTest

import

kotlin.test.Test

import

kotlin.test.assertEquals

// The suspending function under test

suspend fun greet

(

name

:

String

)

:

String

{

    delay

(

1000

)

 

// Simulate a time-consuming operation, skipped by virtual time in runTest

   

return

"Hello, $name"

}

class

GreetTest

{

    @Test

    fun greetReturnsGreeting

(

)

=

runTest

{

       

// The whole test finishes instantly and does not really wait 1 second

        assertEquals

(

"Hello, Runoob"

, greet

(

"Runoob"

)

)

   

}

}

If the code under test launches coroutines internally, runTest waits for them to finish before the test ends, avoiding the illusion of "the test passed but coroutines are still running".

Tip:runTest returns a TestScope, and you can use testScheduler.advanceTimeBy(1000) to manually advance virtual time to verify timeout or delay logic.


Running tests with Gradle

Gradle's test task compiles and runs all tests while generating an HTML report.

During development you often only need to run a single test class or method; use the --tests parameter to filter.

Command Purpose
./gradlew test Run all tests
./gradlew test --tests "com.runoob.CalculatorTest" Run only the specified test class
./gradlew test --tests "*CalculatorTest.addReturnsSumOfTwoNumbers" Run only the specified test method
./gradlew test --info Output detailed logs to help diagnose failures
./gradlew test --rerun-tasks Ignore incremental cache and force re-execution
./gradlew clean test Clean, then rebuild and test

The test report is generated by default at build/reports/tests/test/index.html; open it in a browser to see the result and duration of each case.



$ ./gradlew test --tests "com.runoob.CalculatorTest"



> Task :test

BUILD SUCCESSFUL in 1s



3 tests completed, 3 passed

In continuous integration environments, --no-daemon is usually added to the test command to avoid the daemon occupying memory.


Common questions

Below are the most common pitfalls when first writing tests.

Tests cannot find the @Test annotation

Check whether the imported package is kotlin.test.Test or org.junit.jupiter.api.Test; the two cannot be mixed.

Just use one consistently within the same test class; kotlin.test annotations delegate to JUnit on the JVM.

useJUnitPlatform is not configured

JUnit 5 must explicitly declare tasks.test { useJUnitPlatform() }; otherwise Gradle defaults to the JUnit 4 platform and the tests will not be executed at all.

Dependencies between tests cause unstable results

Every test method should be independent and not rely on execution order.

Rebuild shared state in @BeforeTest rather than creating it once during class initialization.

Tests run slowly

First check whether you are really waiting on a network or database. Skip delay in coroutines with runTest, and replace external dependencies with fakes.

Run only the affected test classes instead of the full suite every time.