Power-assert

suggest change

A failing assertTrue(x) reports Expected value to be true. and nothing more. To find out why it failed you add a message, a println, or open the debugger.

Power-assert is a Kotlin compiler plugin that rewrites calls to assertion functions you pick. When an assertion fails, the message shows the source of the call and the value of every subexpression, drawn as a diagram under the code:

assertTrue(order.items.size > 2 && order.total < 20.0)
           |     |     |    |
           |     |     |    false
           |     |     2
           |     [pen, ink]
           Order(id=7, items=[pen, ink], total=12.5)

You keep writing plain assert, require, assertTrue or assertEquals calls with ordinary Kotlin expressions. You don't need a matcher DSL to get a useful failure message.

Versions:

All examples were compiled and run with Kotlin 2.4.21 on JDK 25. The Gradle examples use Gradle 9.8.1.

Before and after

Here is a small program that uses two kotlin.test assertions:

import kotlin.test.assertEquals
import kotlin.test.assertTrue

data class Order(val id: Int, val items: List<String>, val total: Double)

fun main() {
    val order = Order(7, listOf("pen", "ink"), 12.5)
    try {
        assertTrue(order.items.size > 2 && order.total < 20.0)
    } catch (e: AssertionError) {
        println(e.message)
    }
    try {
        assertEquals(order.items.first().length, order.items.last().length + 1)
    } catch (e: AssertionError) {
        println(e.message)
    }
}

Compiled normally, the failures say very little:

Expected value to be true.
Expected <3>, actual <4>.

Compiled with the Power-assert plugin configured for kotlin.test.assertTrue and kotlin.test.assertEquals, the same code prints:


assertTrue(order.items.size > 2 && order.total < 20.0)
           |     |     |    |
           |     |     |    false
           |     |     2
           |     [pen, ink]
           Order(id=7, items=[pen, ink], total=12.5)


assertEquals(order.items.first().length, order.items.last().length + 1)
             |     |     |       |       |     |     |      |      |
             |     |     |       |       |     |     |      |      4
             |     |     |       |       |     |     |      3
             |     |     |       |       |     |     ink
             |     |     |       |       |     [pen, ink]
             |     |     |       |       Order(id=7, items=[pen, ink], total=12.5)
             |     |     |       3
             |     |     pen
             |     [pen, ink]
             Order(id=7, items=[pen, ink], total=12.5)
. Expected <3>, actual <4>.

Some things to notice:

Setting it up with Gradle

The plugin ships with Kotlin, so its version always matches the Kotlin version:

// build.gradle.kts
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi

plugins {
    kotlin("jvm") version "2.4.21"
    kotlin("plugin.power-assert") version "2.4.21"
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
}

kotlin {
    jvmToolchain(25)
}

@OptIn(ExperimentalKotlinGradlePluginApi::class)
powerAssert {
    functions = setOf(
        "kotlin.assert",
        "kotlin.test.assertTrue",
        "kotlin.test.assertEquals",
        "kotlin.test.assertNull",
    )
}

tasks.test {
    useJUnitPlatform()
}

Without the @OptIn, Gradle prints an "Experimental API in the Kotlin Gradle Plugin" warning for every line of the powerAssert block. The build still works.

The powerAssert extension has three settings:

Property Default Meaning
functions setOf("kotlin.assert") Fully qualified names of the functions to transform
compilationFilter PowerAssertCompilationFilter.TESTS Which compilations are transformed: only test by default
addRuntimeDependency true Adds kotlin-power-assert-runtime as an implementation dependency of the transformed compilations

If you only apply the plugin, it transforms kotlin.assert in test code. Most projects want to add the kotlin.test functions.

Here is the code under test. It has a bug: total ignores the quantity.

// src/main/kotlin/Cart.kt
data class Item(val name: String, val price: Int, val qty: Int = 1)

class Cart {
    private val items = mutableListOf<Item>()

    fun add(item: Item) {
        require(item.qty > 0) { "qty must be positive" }
        items += item
    }

    fun find(name: String): Item? = items.find { it.name == name }

    val count: Int get() = items.size

    override fun toString() = "Cart($items)"

    // bug: ignores qty
    val total: Int get() = items.sumOf { it.price }
}

And the tests:

// src/test/kotlin/CartTest.kt
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class CartTest {
    private val cart = Cart().apply {
        add(Item("pen", 3, qty = 2))
        add(Item("notebook", 7))
    }

    @Test
    fun total() {
        assertEquals(3 * 2 + 7, cart.total)
    }

    @Test
    fun countAndTotal() {
        assertTrue(cart.count == 2 && cart.total > 10)
    }

    @Test
    fun missingItem() {
        assertNull(cart.find("notebook"))
    }
}

gradle test fails all three tests. The console only prints AssertionFailedError at CartTest.kt:14. The full messages are in the HTML report under build/reports/tests/test, and in the console if you set testLogging { exceptionFormat = TestExceptionFormat.FULL }:

org.opentest4j.AssertionFailedError: 
assertEquals(3 * 2 + 7, cart.total)
               |   |    |    |
               6   13   |    10
                        Cart([Item(name=pen, price=3, qty=2), Item(name=notebook, price=7, qty=1)])
 ==> expected: <13> but was: <10>

org.opentest4j.AssertionFailedError: 
assertTrue(cart.count == 2 && cart.total > 10)
           |    |     |       |    |     |
           |    2     true    |    10    false
           |                  Cart([Item(name=pen, price=3, qty=2), Item(name=notebook, price=7, qty=1)])
           Cart([Item(name=pen, price=3, qty=2), Item(name=notebook, price=7, qty=1)])

org.opentest4j.AssertionFailedError: 
assertNull(cart.find("notebook"))
           |    |
           |    Item(name=notebook, price=7, qty=1)
           Cart([Item(name=pen, price=3, qty=2), Item(name=notebook, price=7, qty=1)])
 ==> expected: <null> but was: <Item(name=notebook, price=7, qty=1)>

Values are printed with toString(). If Cart didn't override it, you would see Cart@4e07b95f. Data classes and readable toString() implementations make the diagrams much more useful.

The tests run on the JUnit Platform, as in Parameterized tests and Testing in CI. Power-assert only changes how the assertion calls are compiled, so it works with any test runner.

Which functions can be transformed

The plugin can transform a function when one of its overloads takes a message as the last parameter, either String or () -> String. It rewrites f(args) into a call to that overload and passes the diagram as the message:

If you pass your own message, the plugin keeps it and puts the diagram after it.

When no such overload exists, the compiler warns and leaves the call unchanged:

fun myCheck(cond: Boolean) { if (!cond) throw AssertionError("failed") }
fun msgCheck(cond: Boolean, msg: String) { if (!cond) throw AssertionError(msg) }

fun main() {
    val x = 3
    try { myCheck(x > 5) } catch (e: AssertionError) { println(e.message) }
    try { msgCheck(x > 5, "x too small") } catch (e: AssertionError) { println(e.message) }
}

Compiled with function=myCheck and function=msgCheck (top-level functions in the default package):

warning: unable to find overload of function 'myCheck' for Power-Assert transformation callable as:
 - myCheck(String)
 - myCheck(() -> String)
 - myCheck(kotlin.Boolean, String)
 - myCheck(kotlin.Boolean, () -> String)
failed
x too small
msgCheck(x > 5, "x too small")
         | |
         | false
         3

Java methods work too. JUnit's org.junit.jupiter.api.Assertions.assertTrue(boolean, String) qualifies:

import org.junit.jupiter.api.Assertions

fun main() {
    val nums = listOf(1, 2, 3)
    try {
        Assertions.assertTrue(nums.sum() > 10, "sum too small")
    } catch (e: AssertionError) {
        println(e.message)
    }
}

With function=org.junit.jupiter.api.Assertions.assertTrue:

sum too small
assertTrue(nums.sum() > 10, "sum too small")
           |    |     |
           |    |     false
           |    6
           [1, 2, 3]
 ==> expected: <true> but was: <false>

Reading the diagrams

Every subexpression that produces a value gets a column, and the value is printed under its operator or name. Literals like 3, "admin" and 1 are not repeated. Here are some common expression shapes:

data class User(val name: String, val email: String?, val roles: Set<String>)

fun show(label: String, block: () -> Unit) {
    try {
        block()
    } catch (e: AssertionError) {
        println("== $label")
        println(e.message)
    }
}

fun main() {
    val user = User("ann", null, setOf("viewer"))
    val admins = listOf("bob", "eve")

    show("in") { assert("admin" in user.roles || user.name in admins) }
    show("safe call and elvis") { assert((user.email?.length ?: 0) > 3) }
    show("string template") { assert("${user.name}@example.com" == user.email) }
    show("is") { val any: Any = user.roles; assert(any is List<*>) }
    show("lambda") { assert(user.roles.count { it.startsWith("ad") } == 1) }
}
== in

assert("admin" in user.roles || user.name in admins)
               |  |    |        |    |    |  |
               |  |    |        |    |    |  [bob, eve]
               |  |    |        |    |    false
               |  |    |        |    ann
               |  |    |        User(name=ann, email=null, roles=[viewer])
               |  |    [viewer]
               |  User(name=ann, email=null, roles=[viewer])
               false

== safe call and elvis

assert((user.email?.length ?: 0) > 3)
        |    |      |            |
        |    |      |            false
        |    |      null
        |    null
        User(name=ann, email=null, roles=[viewer])

== string template

assert("${user.name}@example.com" == user.email)
       |  |    |                  |  |    |
       |  |    |                  |  |    null
       |  |    |                  |  User(name=ann, email=null, roles=[viewer])
       |  |    |                  false
       |  |    ann
       |  User(name=ann, email=null, roles=[viewer])
       ann@example.com

== is

assert(any is List<*>)
       |   |
       |   false
       [viewer]

== lambda

assert(user.roles.count { it.startsWith("ad") } == 1)
       |    |     |                             |
       |    |     |                             false
       |    |     0
       |    [viewer]
       User(name=ann, email=null, roles=[viewer])

kotlin.assert only throws when JVM assertions are enabled (java -ea, which Gradle's test task enables by default). Kotlin's assert is an ordinary function, though, so its argument is always evaluated, with or without -ea and with or without the plugin:

fun expensive(): Boolean { println("expensive() called"); return false }

fun main() {
    assert(expensive())
    println("done")
}
-- java (no -ea)
expensive() called
done
-- java -ea
expensive() called
Exception in thread "main" java.lang.AssertionError: 
assert(expensive())
       |
       false

Transforming require and check in production code

By default only test code is transformed. Precondition failures in main code can also benefit, so you can switch the filter to ALL:

import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.powerassert.gradle.PowerAssertCompilationFilter

@OptIn(ExperimentalKotlinGradlePluginApi::class)
powerAssert {
    functions = setOf(
        "kotlin.require",
        "kotlin.test.assertTrue",
        "kotlin.test.assertEquals",
        "kotlin.test.assertNull",
    )
    compilationFilter = PowerAssertCompilationFilter.ALL
}

Now Cart.add(Item("eraser", 1, qty = 0)) fails with:

java.lang.IllegalArgumentException: qty must be positive
require(item.qty > 0) { "qty must be positive" }
        |    |   |
        |    0   false
        Item(name=eraser, price=1, qty=0)

compilationFilter takes any PowerAssertCompilationFilter, which is a fun interface that gets a KotlinCompilation. You can write your own, for example compilationFilter = PowerAssertCompilationFilter { it.name == "integrationTest" }.

Before you do this for production code, consider what it costs:

Many teams therefore keep the default and transform only tests. Plain require and check are covered in Assertions.

Using the plugin with kotlinc

The compiler plugin jar is in the Kotlin distribution (lib/power-assert-compiler-plugin.jar). On the command line you pass it with -Xplugin and list the functions with -P:

kotlinc Intro.kt -cp "$KOTLIN_HOME/lib/kotlin-test.jar" \
  -Xplugin="$KOTLIN_HOME/lib/power-assert-compiler-plugin.jar" \
  -P plugin:org.jetbrains.kotlin.powerassert:function=kotlin.test.assertTrue,plugin:org.jetbrains.kotlin.powerassert:function=kotlin.test.assertEquals \
  -d out

Unlike the Gradle plugin, the command-line plugin has no default function list. If you don't pass -P ...:function=kotlin.assert, nothing is transformed. The plugin doesn't warn about this.

Writing your own Power-assert functions

The function= list works for existing functions that have a message overload. Kotlin 2.4 adds a more direct way. Annotate your function with @PowerAssert, and inside it read PowerAssert.explanation to get a structured description of the call site. These functions are transformed automatically, so you don't list them in functions.

The API is in kotlin-power-assert-runtime (package kotlin.powerassert). The Gradle plugin adds this library to transformed compilations for you. With plain kotlinc, put kotlin-power-assert-runtime-jvm-2.4.21.jar on the classpath.

As an example, here are soft assertions: they collect every failed expectation and report them together. For a failed ==, they also print both sides:

@file:OptIn(ExperimentalPowerAssert::class)

import kotlin.powerassert.EqualityExpression
import kotlin.powerassert.ExperimentalPowerAssert
import kotlin.powerassert.PowerAssert
import kotlin.powerassert.toDefaultMessage

class SoftAssertions {
    private val failures = mutableListOf<String>()

    @PowerAssert
    fun expect(condition: Boolean) {
        if (condition) return
        val explanation = PowerAssert.explanation
        if (explanation == null) {
            failures += "expectation failed"
            return
        }
        // find the first == that evaluated to false and describe it
        val eq = explanation.expressions
            .filterIsInstance<EqualityExpression>()
            .firstOrNull { it.value == false }
        val hint = if (eq != null) "\n  left:  ${eq.lhs}\n  right: ${eq.rhs}" else ""
        failures += explanation.toDefaultMessage().trimEnd() + hint
    }

    fun assertAll() {
        if (failures.isNotEmpty()) {
            throw AssertionError(
                "${failures.size} expectation(s) failed:\n\n" + failures.joinToString("\n\n")
            )
        }
    }
}

fun softly(block: SoftAssertions.() -> Unit) = SoftAssertions().apply(block).assertAll()

data class Config(val host: String, val port: Int, val tags: List<String>)

fun main() {
    val cfg = Config("localhost", 8443, listOf("dev"))
    try {
        softly {
            expect(cfg.host == "example.com")
            expect(cfg.port in 1..1024)
            expect(cfg.tags.size == 1)
            expect("prod" in cfg.tags)
        }
    } catch (e: AssertionError) {
        println(e.message)
    }
}
3 expectation(s) failed:

expect(cfg.host == "example.com")
       |   |    |
       |   |    false
       |   "localhost"
       Config(host=localhost, port=8443, tags=[dev])
  left:  localhost
  right: example.com

expect(cfg.port in 1..1024)
       |   |    |   |
       |   8443 |   1..1024
       |        false
       Config(host=localhost, port=8443, tags=[dev])

expect("prod" in cfg.tags)
              |  |   |
              |  |   [dev]
              |  Config(host=localhost, port=8443, tags=[dev])
              false

The pieces of the API:

explanation is nullable for a reason. A @PowerAssert function compiled into a library can be called from code compiled without the plugin. If SoftAssertions is compiled with the plugin and main without it, every failure takes the fallback branch:

3 expectation(s) failed:

expectation failed

expectation failed

expectation failed

If the @PowerAssert function itself is compiled without the plugin, reading PowerAssert.explanation throws NotImplementedError: Intrinsic property! Make sure the Power-Assert compiler plugin is applied to your build.. The ?. on the result doesn't protect you, because the getter itself throws.

Power-assert vs. assertion libraries

Assertion libraries such as Kotest assertions, AssertJ and Strikt solve the same problem differently. You express the check through their API (cart.total shouldBe 13, assertThat(list).containsExactly(...)) and the library knows what you meant.

Power-assert Assertion library
How you write checks Plain Kotlin expressions in assert/assertTrue/assertEquals Library matchers and DSL
Failure message Source line plus every intermediate value Matcher-specific: collection diffs, "missing element X", string diffs
Learning curve None beyond Kotlin Must learn the matcher vocabulary
Dependencies Compiler plugin, part of Kotlin Extra library
Collections and strings Shows both values, you compare them yourself Detailed diffs (missing, extra, first differing index)
Stability Experimental in Kotlin 2.4 Stable, mature

The two can be combined. Use Power-assert for the many simple boolean and equality checks, and a library matcher where its diff output helps, for example to compare two large lists. Library authors can also annotate their own functions with @PowerAssert so the call site shows up in their failure messages.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents