How to use MicronautTest with Kotlintest to inject beans while testing ? in Kotlin

Viewed 1059

How to inject the following into Test, as no constructor args are allowed and its failed to initialise the injected beans

@MicronautTest
class ApplicationTest:StringSpec() {

    @Inject
    lateinit val embeddedServer:EmbeddedServer;

    @Inject
    lateinit val dataSource:DataSource

    init{
        "test something"{
            //arrange act assert
        }
    }
}
3 Answers

You need to specify Project config by creating an object that is derived from AbstractProjectConfig, name this object ProjectConfig and place it in a package called io.kotlintest.provided. KotlinTest will detect it's presence and use any configuration defined there when executing tests. as per the documentation https://github.com/kotlintest/kotlintest/blob/master/doc/reference.md#project-config

object ProjectConfig :AbstractProjectConfig() {
override fun listeners() = listOf(MicornautKotlinTestExtension)
override fun extensions() = listOf(MicornautKotlinTestExtension)
}

Have you tried to write your code like this ?

@MicronautTest
class ApplicationTest:StringSpec() {

    val embeddedServer:EmbeddedServer

    val dataSource:DataSource


    @Inject
    ApplicationTest(embeddedServer:EmbeddedServer, dataSource:DataSource) {
      this.embeddedServer = embeddedServer
       this.dataSource = dataSource
    }

    init{
        "test something"{
            //arrange act assert
        }
    }
}

This should work.

Related