InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
8.78k stars 698 forks source link

Unit Test KMP #1717

Open Egi10 opened 7 months ago

Egi10 commented 7 months ago

Describe the bug I have an expect / actual fun in KMP which is like this:

// Common
expect fun getPlatform(): Platform

// Android
class AndroidPlatform : Platform, KoinComponent {
    private val context by inject<Context>()

    ...

}
actual fun getPlatform(): Platform = AndroidPlatform()

// iOS
class IosPlatform : Platform {
 ...
}
actual fun getPlatform(): Platform = IosPlatform()

To Reproduce While performing unit testing on a class that utilizes getPlatform(), I encountered an error:

KoinApplication has not been started
java.lang.IllegalStateException: KoinApplication has not been started
    at org.koin.core.context.GlobalContext.get(GlobalContext.kt:36)
    at org.koin.core.component.KoinComponent$DefaultImpls.getKoin(KoinComponent.kt:33)
    at cybreed.efisheryprototype.shared.core.AndroidPlatform.getKoin(Platform.kt:13)
    at cybreed.efisheryprototype.shared.core.AndroidPlatform$special$$inlined$inject$default$1.invoke(KoinComponent.kt:75)

I know this is due to using Koin Component and accessing Context in the Android actual function. Is there a way to perform Unit Tests for this without encountering the mentioned error?

Koin module and version:

arnaudgiuliani commented 5 months ago

it's using AndroidPlatform and KoinComponent. This is why you need to start Koin before using it.

Egi10 commented 5 months ago

How do I start using Start Koin in commonMain? I always encounter errors when AndroidComponent injects Context.

arnaudgiuliani commented 5 months ago

AndroidComponent injects Context.

this part needs to be in android part only. Check one of the KMP sample to help understand (https://insert-koin.io/docs/quickstart/kmp)

Egi10 commented 5 months ago

I'm facing an issue with Unit Test. In the Repository (commonMain), there's an access to expect getPlatform, where there's a KoinComponent accessing Context. When I run the unit test, I encounter an error. Should I run the unit test in androidMain?

arnaudgiuliani commented 4 months ago

running unit tests from common code should ask you to run on a platform.

Can you paste your code snippet?