Last active
July 19, 2018 09:08
-
-
Save Sloy/b64226a64c86ece8af5225bf4ff9b0b3 to your computer and use it in GitHub Desktop.
Reproducing issue with Koin shared state in Android Tests. Inspired by the Dagger 1 version: https://gist.github.com/Sloy/c45dc3291403e603b4b88755e4a67660
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open class Counter(context: Context) { | |
open var count: Int = 0 | |
open fun hit() = count++ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyApplication : Application() { | |
val mainModule = module { | |
single { Counter(get()) } | |
} | |
override fun onCreate() { | |
super.onCreate() | |
startKoin(this, listOf(mainModule)) | |
} | |
} |
An improved version is by extracting the Koin initialization to its own object, and reusing it from the Application and from tests to avoid duplication.
object KoinLoader {
private val modules = listOf(mainModule)
fun init(context: Context) {
val app = context.applicationContext as Application
app.startKoin(app, modules)
}
fun reload(context: Context) {
closeKoin()
init(context)
}
}
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
KoinLoader.init(this)
}
}
class MyTest {
@Before
fun setUp() {
KoinLoader.reload(getTargetContext())
}
}
Even more improved: Create a JUnit rule and apply it to all your tests. That way you make sure you never share Koin state between tests.
class ReloadKoinRule : MethodRule {
override fun apply(statement: Statement, frameworkMethod: FrameworkMethod, testClassInstance: Any): Statement {
return object : Statement() {
override fun evaluate() {
KoinLoader.reload(getTargetContext())
statement.evaluate()
KoinLoader.reload(getTargetContext())
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One way to fix it: