5

This is my application test class

class ApplicationTest {
    private val heroRepository: HeroRepository by inject(HeroRepository::class.java)

    @OptIn(InternalAPI::class)
    @Test
    fun `access all heroes endpoints, assert correct information`() = testApplication {

        val response = client.get("/naruto/heroes")
        assertEquals(
            expected =
            """
                    {
                    success = true,
                    message = "ok",
                    prevPage = null,
                    nextPage = 2,
                    heroes = ${heroRepository.heroes[1]!!}
                    }
                """.trimIndent()  ,
            actual = response.bodyAsText()
        )
    }
}

It show the error of java.lang.ClassCastException when heroRepository is getting inject and i am using koin for dependency injection

java.lang.ClassCastException: class com.example.repository.HeroRepositoryImpl cannot be cast to class com.example.repository.HeroRepository (com.example.repository.HeroRepositoryImpl is in unnamed module of loader io.ktor.server.engine.OverridingClassLoader$ChildURLClassLoader @7f6ad6c8; com.example.repository.HeroRepository is in unnamed module of loader 'app')

And this is my AllHeroesRoute and here it's perfectly injecting heroRepository

fun Route.getAllHeroes() {

    val heroRepository: HeroRepository by inject()

    get("/naruto/heroes") {
        try {
            val page = call.request.queryParameters["page"]?.toInt() ?: 1
            require(page in 1..5)
            val apiResponse = heroRepository.getAllHeroes(page = page)
            call.respond(
                message = apiResponse,
                status = HttpStatusCode.OK
            )
        } catch (e: NumberFormatException) {
            call.respond(
                message = ApiResponse(success = false, message = "Only numbers allowed"),
                status = HttpStatusCode.BadRequest
            )
        } catch (e: IllegalArgumentException) {
            call.respond(
                message = ApiResponse(success = false, message = "Heroes Not Found"),
                status = HttpStatusCode.BadRequest
            )
        }
    }
}
  • 1
    Most likely this is a bug https://youtrack.jetbrains.com/issue/KTOR-4164. Unfortunately, auto-reloading is on when development mode is on, and in the test environment, it's always the case so I don't know how to work it around. – Aleksei Tirman Jun 06 '22 at 09:58

1 Answers1

7

I had the same issue, disabling the developmentMode fixed it:

fun myTestFunc() = testApplication {
    environment {
        developmentMode = false
    }
    ....
}
    
ayun12
  • 479
  • 1
  • 4
  • 9