gpt4 book ai didi

android - 如何在 Koin 的仪器测试中注入(inject)使用 androidContext 的类?

转载 作者:行者123 更新时间:2023-11-29 00:56:19 28 4
gpt4 key购买 nike

我的一个类具有 Context 类型的依赖项。在将 Koin 添加到我的项目之前,我通过对我的 Application 类的硬依赖对其进行了初始化:

class ProfileRepository(
private var _context: Context? = null,
private var _profileRestService: IProfileRestService? = null
) : IProfileRepository {

init {
if (_context == null) {
_context = MyApplication.getInstance().applicationContext
}
}

现在,我想使用 Koin 来注入(inject)这个依赖项。这就是我定义模块的方式:

object AppModule {

@JvmField
val appModule = module {
single<IProfileRestService> { ProfileRestService() }
single<IProfileRepository> { ProfileRepository(androidContext(), get()) }
}
}

我在我的应用程序类(用 Java 编写)的 onCreate 方法中启动 Koin:

startKoin(singletonList(AppModule.appModule));

我想用仪器测试而不是单元测试来测试这个类,因为我想使用真实的上下文而不是模拟。这是我的测试:

@RunWith(AndroidJUnit4::class)
class MyTest : KoinTest {

private val _profileRepository by inject<IProfileRepository>()

@Test
fun testSomething() {
assertNotNull(_profileRepository)
}

测试失败并出现异常:

org.koin.error.BeanInstanceCreationException: Can't create definition for 'Single [name='IProfileRepository',class='com.my.app.data.profile.IProfileRepository']' due to error :
No compatible definition found. Check your module definition

如果我像这样模拟上下文,我可以让它与单元测试一起工作:

class MyTest : KoinTest {

private val _profileRepository by inject<IProfileRepository>()

@Before
fun before() {
startKoin(listOf(AppModule.appModule)) with mock(Context::class.java)
}

@After
fun after() {
stopKoin()
}

@Test
fun testSomething() {
assertNotNull(_profileRepository)
}

如何让它在真实环境中作为插桩测试工作?

最佳答案

代替(在申请中):

startKoin(applicationContext, modules)

使用模拟上下文:

startKoin(modules) with (mock(Context::class.java))

来自 https://insert-koin.io/docs/1.0/documentation/koin-android/index.html#_starting_koin_with_android_context_from_elsewhere

关于android - 如何在 Koin 的仪器测试中注入(inject)使用 androidContext 的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54580907/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com