koin icon indicating copy to clipboard operation
koin copied to clipboard

Unit Test KMP

Open Egi10 opened this issue 1 year ago • 5 comments

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: [e.g]: koin-core:3.4.3

Egi10 avatar Nov 27 '23 07:11 Egi10

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

arnaudgiuliani avatar Jan 25 '24 10:01 arnaudgiuliani

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

Egi10 avatar Jan 25 '24 20:01 Egi10

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)

arnaudgiuliani avatar Jan 30 '24 12:01 arnaudgiuliani

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?

Egi10 avatar Feb 05 '24 02:02 Egi10

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

Can you paste your code snippet?

arnaudgiuliani avatar Feb 15 '24 15:02 arnaudgiuliani

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 15 '24 02:07 stale[bot]