Hi guys, I am struggling with testing my ktor app ...
# ktor
a
Hi guys, I am struggling with testing my ktor app have anyone any idea what can cause it? https://stackoverflow.com/questions/77602947/mocked-use-cases-in-ktor-kotest-koin-mockk-not-working-as-expected-in-endpoint-t
a
By default, the
testApplication
tries to load the configuration from the
application.conf
which triggers the execution of the module function. Because of that, your application establishes the connection to MondoDB in the tests. To avoid that, you can override the configuration:
Copy code
testApplication {
    environment {
        config = MapApplicationConfig()
    }
    // ...
}
a
Thank you so much Aleksei
Copy code
class UserRoutesTest: KoinTest {

    private val getUserInfoUseCase: GetUserInfoUseCase by inject()
    private val getUserOffersUseCase: GetUserOffersUseCase by inject()
    val fakeUser = MockUserDtoService().randomBasicUserDto()
    val userId = fakeUser.id


    @BeforeEach
    fun setUp() {
        stopKoin() // Ensure no previous Koin instance is running

    }

    @AfterEach
    fun tearDown() {
        stopKoin() // Zatrzymaj Koin po każdym teście
    }


    @Test
    fun `GET user by userId returns user info`() = testApplication {
        environment {
            config = MapApplicationConfig("ktor.environment" to "dev")
        }
        application {
            configure()  // Make sure to include this
            coEvery {
                getUserInfoUseCase.getBasicInfo(any())
            } returns fakeUser
        }

        this.client.get("/user/$userId").apply {
            val responseBody = bodyAsText()
            assertEquals(HttpStatusCode.OK, status)
            assertNotNull(responseBody)
        }
    }

    @Test
    fun `GET user offers by user id`() = testApplication {
        environment {
            config = MapApplicationConfig("ktor.environment" to "dev")
        }
        application {
            configure()  // Make sure to include this
            coEvery {
                getUserOffersUseCase(any())
            } returns PostedOffersDto(fakeUser.postedOffers)
        }

        this.client.get("/user/$userId/offers").apply {
            val responseBody = bodyAsText()
            assertEquals(HttpStatusCode.OK, status)
            assertNotNull(responseBody)
        }
    }

    private fun Application.configure() {
        startKoin {
            modules(listOf(appModule, databaseModule, categoryModule, offerModule, testUserModule, authModule))
        }
        configureSecurity()
        configureSerialization()
        configureStatusPages()
        this.routing {
            userRoutes()
        }
    }
}