Hey, devs. I would like to know your thoughts on t...
# koin
a
Hey, devs. I would like to know your thoughts on testing Koin's custom context. I've set up Koin for one of our SDKs. Since it's for SDK, using a custom context is ideal. But I couldn't find any solution for the testing setup in the document. So, I came out with a solution for now. If you've faced this scenario, can you please share your solution? I really appreciate any help you can provide. Reference for Context Isolation https://insert-koin.io/docs/reference/koin-core/context-isolation/
m
Do you need to use more Koin context in the tests? If you need one context (global context), just follow: https://insert-koin.io/docs/reference/koin-test/testing For more contexts, just create own Koin instance for each non-global context:
Copy code
class MyClass

val sdkModule = module {
    singleOf(::MyClass)
}

class MyTest {
    private val sdkKoinApp = koinApplication {
        // declare used modules
        modules(sdkModule)
    }
    private val sdkKoin = sdkKoinApp.koin

    val myClass by sdkKoin.inject<MyClass>()

    // ...
}
BTW KoinTest is actually KoinComponent, which use global context by default.
Own Koin instance supports
inject
,
get
,
declare
,
declareMock
and
checkModules
like
KoinTest
.
a
@Martin Sloup Thanks for the reply. Let me provide more context. This is the sample structure before the solution.
Copy code
class SampleA
class SampleB: CustomComponent {
  val sampleA by inject<SampleA>()
}   

object CustomContext {
   // provide koinApp by constructing
   val koin: Koin = koinApp.koin
}

abstract class CustomComponent: KoinComponent {
   override fun getKoin(): Koin = CustomContext.koin
}
The issue is in testing SampleB class. As you mentioned, we cannot use KoinTest because it overrides GlobalContext's koin only.
My current approach is that I customized CustomContext to be able to override the koin variable from the Test class. It works because injections are loaded lazily. I am looking for other possible solutions that are elegant before we actually adapt it. Thanks