使用 Koin 进行正确的仪器测试

ror*_*ror 1 android android-instrumentation koin

无法让这个东西正常工作。

  1. 我在测试运行程序下注册了自定义测试应用程序:
class HelloInstrumentationTestRunner : AndroidJUnitRunner() {
    override fun newApplication(
        cl: ClassLoader?, className: String?, context: Context?
    ): Application {
        return Instrumentation.newApplication(HelloTestApp::class.java, context)
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 我的应用程序实例像往常一样启动:
        startKoin {
            androidLogger()
            androidContext(applicationContext)
            fragmentFactory()
            modules(appModule + viewModelsModule)
        }
Run Code Online (Sandbox Code Playgroud)
  1. 问题 1:在我的仪器测试中,我无法做到stopKoin()(说没有配置 Koin 上下文。请使用 startKoin 或 koinApplication DSL)
  2. 问题 2:当我尝试使用 @After 中的 unloadKoinModules/loadKoinModules 解决这种情况时,我的declareMock后续测试方法不再起作用。

所有这些问题基本上都是因为应用程序实例在测试之间仍然存在,因此 Android 应用程序实例内部配置的图形也在测试之间仍然存在。我需要这种情况不要发生,或者至少能够在测试之间修改图表。

ror*_*ror 5

解决了。

  1. 我必须设置覆盖模块:
    val overrideModule = module(override = true) {
        single<Repository1> {
            mock(Repository1::class.java)
        }
        single { Repository2(get(), get()) }
        single<Repository3> {
            mock(Repository3::class.java)
        }
        ...
    }
Run Code Online (Sandbox Code Playgroud)
  1. 在我的@BeforeTest 中,我现在这样做loadKoinModules(overrideModule)
  2. 在我的@AfterTest 中,我这样做unloadKoinModules(overrideModule)
  3. 在我的测试中,我现在可以执行以下操作:
        given(get<Repository1>().magicCall()).willReturn(
            MagicData(
                "1111",
                Calendar.getInstance().timeInMillis
            )
        )
Run Code Online (Sandbox Code Playgroud)

无需处理 stopKoin 之类的东西,超级简单!