Kotest Compiler Matchers

Explains compiler matchers.

The kotest-assertions-compiler extension provides matchers for checking whether specified Kotlin code snippets compile. This extension is a wrapper around kotlin-compile-testing and provides the following matchers.

  • String.shouldCompile()
  • String.shouldNotCompile()
  • File.shouldCompile()
  • File.shouldNotCompile()

To add compiler matchers, add the following dependency to your project.

testImplementation("io.kotest.extensions:kotest-assertions-compiler:${version}")

Usage:

class CompilationTest: StringSpec() {
    init {
        "shouldCompile test" {
            val codeSnippet = """ val aString: String = "A valid assignment" """.trimMargin()

            codeSnippet.shouldCompile()
            File("SourceFile.kt").shouldCompile()
        }

        "shouldNotCompile test" {
            val codeSnippet = """ val aInteger: Int = "A invalid assignment" """.trimMargin()

            codeSnippet.shouldNotCompile()
            File("SourceFile.kt").shouldNotCompile()
        }
    }
}

While checking compilation of a code snippet, the classpath of the calling process is inherited, so all dependencies available to the calling process are also available while compiling the snippet.

Matchers for checking whether specified Kotlin code compiles:

Matcher Description
string.shouldCompile() Checks that the string is valid Kotlin code.
file.shouldCompile() Checks that the file contains valid Kotlin code.

References