Power Assert now in Kotlin!
Power Assert now in Kotlin! 관련
Even though it passed under most people's radar, to me, it is one of the most important announcements of Kotlin 2.0: We finally have Power Assert! Is it time to explain what it is and how it works.
The core idea of Power Assert is to provide information about failing assertions in tests, which is often the greatest source of information. Power assertions are one of the most beloved features in the Groovy Spock framework. Now they might be another beloved Kotlin feature
With Power Assert, we do not need libraries like AssertJ. We can just use raw assert and assertEquals, and in case of a failure, we will see complete information about values in each assertion.
To use Power Assert, you need to add plugin, and configure for what functions additional message should be added. It only works for functions that specify message on the last parameter. It can also work for require or check if you need it to.
plugins {
kotlin("jvm") version "2.0.0"
kotlin("plugin-power-assert") version "2.0.0"
application
}
powerAssert {
functions = listOf("kotlin.assert", "kotlin.test.assertEquals")
}
plugins {
kotlin("jvm") version "2.0.0"
kotlin("plugin-power-assert") version "2.0.0"
application
}
powerAssert {
functions = ["kotlin.assert", "kotlin.test.assertEquals"]
}
How how does it work? This feature is based on the backend compiler plugin IrGenerationExtension. I explained it in detail in the book Advanced Kotlin, but the short explanation is that it is a compiler plugin that transforms our code during compilation.
Power Assert uses IrGenerationExtension to transform functions, specifying their message. It transforms those functions that we specify in this plugin configuration. So what does it actually do?
It extracts each expression into a variable. This must be done so that those expressions are executed only once! Then, it uses those variables for assertions and constructing messages. If an assertion already has a message, it is appended.
The tricky part is constructing a message that looks exactly like the original code and includes indents in the correct places. It was a titanic work by Brian Norman (bnormcodes
), who spent over four years to make it work that well! Great kudos!