Home > Blockchain >  Gradle Kotest KMongo Coroutines - Could not create instance of class
Gradle Kotest KMongo Coroutines - Could not create instance of class

Time:09-27

I'm writing a small application in Kotlin that uses KMongo coroutines and I want to use Kotest as the testing framework.
I wrote a simple test to access a database and retrieve a document:

class KabotMultiDBClientTest : StringSpec({

    val client = KabotMultiDBClient(
        mapOf(
            System.getenv("TEST_DB_ID")!! to MongoCredentials(
                System.getenv("DB_TEST_USER")!!,
                System.getenv("DB_TEST_PWD")!!,
                System.getenv("TEST_DB")!!,
                System.getenv("DB_TEST_IP")!!,
                System.getenv("DB_TEST_PORT")!!.toInt(),
            )
        )
    )

    "dummy test" { true shouldBe true }

})

When I test it using the IntelliJ Kotest plugin it works but If I use the

./gradlew kotest

command I receive this error.

Could not create instance of class org.wagham.db.KabotMultiDBClientTest

If I remove the client instantiation the the gradle task works without problems.
This is the code of the class:

class KabotMultiDBClient(
    credentials: Map<String, MongoCredentials>
) {

    private val databaseCache = credentials.keys.fold(mapOf<String, CoroutineDatabase>()) { acc, guildId ->
        credentials[guildId]?.let {
            acc   (guildId to
                    KMongo.createClient("mongodb://${it.username}:${it.password}@${it.ip}:${it.port}/${it.database}").coroutine.getDatabase(it.database))
        } ?: throw InvalidCredentialsExceptions(guildId)
    }

    suspend fun getActiveCharacter(guildId: String, playerId: String): org.wagham.db.models.Character {
        return databaseCache[guildId]?.let {
            val col = it.getCollection<org.wagham.db.models.Character>("characters")
            col.findOne(Document(mapOf("status" to "active", "player" to playerId)))
        } ?: throw InvalidGuildException(guildId)
    }
}

What could be the origin of the error?

CodePudding user response:

I found the error, and it was far more trivial than I imagined: apparently, gradlew launched from the Windows terminal couldn't read the environment variables.

I modified the build.gradle.kts file in this way and everything worked fine:

tasks.withType<Test> {
    useJUnitPlatform()
    environment("VAR1", "value 1")
    environment("VAR2", "value 2")
    environment("VARN", "value N")
}
  • Related