kotlinkotlintest

How to use beforeProject in kotlintest?


I've implemented a TestListener as follows:

object IntegrationTest: TestListener {
    override fun beforeProject() {
        println("integration tests - beforeProject")
    }

    override fun beforeSpec(description: Description, spec: Spec) {
        println("integration tests - beforeSpec")
    }
}

And used it in a test:

class SimpleTest: StringSpec() {

    override fun listeners() = listOf(IntegrationTest)

    init {
        "it - 1" {
            println("it - 1")
        }

        "it - 2" {
            println("it - 2")
        }
    }
}

The problem is that integration tests - beforeProject is never printed in the output.

The result is:

integration tests - beforeSpec
it - 1
it - 2

I tried it in intellij and using gradle CLI. Am I missing something?


Solution

  • beforeProject has to run before any tests are discovered, otherwise it's not really before the project but would kind of be "before any tests have executed" (The difference might not be important in your use class, but KotlinTest mantains the distinction).

    Therefore overriding that method in a listener that's added to a test class doesn't do anything (as you have seen).

    So instead you need to add your listener to ProjectConfig which is project wide configuration. You do this by subclassing AbstractProjectConfig and putting it in a special package name, like this:

    package io.kotlintest.provided

    object ProjectConfig : AbstractProjectConfig() {
      // add listeners here
    }
    

    See full docs here: https://github.com/kotlintest/kotlintest/blob/master/doc/reference.md#project-config