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

标签 android junit kotlin dependency-injection koin

我的一个类具有 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()) }
    }
}

我在我的 Application 类(用 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/

相关文章:

Android 立即检测到蓝牙断开连接

android - 了解 Android 的 <layer-list>

java - Jenkins 测试失败

intellij-idea - 如何使用 VisualVM 分析从 Intellij Idea 运行的 JUnit 测试

java - 如何解决 Kotlin 多平台库项目中的 lambda/SAM 问题?

android - 如果为其他应用授予 REQUEST_INSTALL_PACKAGES 权限,则无法检索

java - 不支持的媒体类型 - HTTP 状态 415

android - sudo adb devices 后ADB无法启动或找不到设备

java - 如何使用EasyMock.capture捕获传入参数?

android - 如何从 Kotlin 中的 MultiSelectSpinner 获取逗号分隔的项目 ID