Swanand Keskar
Swanand Keskar

Reputation: 1073

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

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
        }
    }
}

Upvotes: 2

Views: 1632

Answers (3)

Swanand Keskar
Swanand Keskar

Reputation: 1073

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)
}

Upvotes: 3

James Kleeh
James Kleeh

Reputation: 12228

Because the test cases are passed like a lambda to the parent class constructor, you have to use constructor injection

@MicronautTest
class ApplicationTest(
    private val embeddedServer: EmbeddedServer,
    private val dataSource: DataSource
): StringSpec({

    "test something"{
        //arrange act assert
    }

})

You can look at any of the tests in the project for a running example. https://github.com/micronaut-projects/micronaut-test/blob/master/test-kotlintest/src/test/kotlin

Upvotes: 1

Xavier Bouclet
Xavier Bouclet

Reputation: 1012

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.

Upvotes: 0

Related Questions