Skip to content

Robolectric App tests get a closed Koin in composables #1557

@yschimke

Description

@yschimke

Describe the bug

Using Koin with Robolectric, fails with

Scope '_root_' is closed
org.koin.core.error.ClosedScopeException: Scope '_root_' is closed
	at org.koin.core.scope.Scope.resolveInstance(Scope.kt:221)
	at org.koin.core.scope.Scope.get(Scope.kt:210)
	at org.koin.androidx.viewmodel.factory.KoinViewModelFactory.create(KoinViewModelFactory.kt:25)
	at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
	at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
	at org.koin.androidx.viewmodel.GetViewModelKt.resolveViewModel(GetViewModel.kt:44)

When it fails, these return different Koin instances in the composable

KoinPlatformTools.defaultContext().get() -> the fresh instance
LocalKoinApplication.current -> the instance from the first test

To Reproduce
Steps to reproduce the behavior:

  1. Checkout https://github.com/joreilly/Confetti/, specifically this PR Enable wear app tests joreilly/Confetti#580
  2. Run tests in wearApp/src/test
  3. Disable the overrides in MainActivity
  4. Run tests again

** workaround **

In main app composable, override

https://github.com/joreilly/Confetti/pull/580/files#diff-0548d0af1b708341bc3c142fbf71b1270fb90f0653f791f2eea9e92867d2e99f

        setContent {
            ConfettiApp(navController, intent)
            // This shouldn't be needed, but allows robolectric tests to run successfully
            // TODO remove once a solution is found or a fix in koin?
            CompositionLocalProvider(
                LocalKoinScope provides KoinPlatformTools.defaultContext().get().scopeRegistry.rootScope,
                LocalKoinApplication provides KoinPlatformTools.defaultContext().get()
            ) {
...

Expected behavior
Tests should pass as there is a fresh Koin instance for the current test

Koin project used and used version (please complete the following information):
3.4.0

Metadata

Metadata

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions