If I have a (simplified) class that looks like this:

class MyManager @JvmOverloads constructor(/*constructor args*/) : MyManagerInterface {

    @Inject
    lateinit var myLogger: MyLogger

    init {
        component = DaggerLoggerComponent.builder()
                .loggerModule(LoggerModule(internalLogger))
                .build()

        component.inject(this)
    }

    companion object {
        lateinit var component: RemoteLoggerComponent
            private set
    }
}

When unit testing, how on earth do I mock the component in the companion object?

我try 过使用Mockito、MockK等各种技巧,但我遇到了几个障碍.

The CUT (class-under-test) is another class that is using the MyManager component to inject its dependencies in its init block like so:

init {
        if(applicationContext == null) {
            throw IllegalStateException("Application Context must not be null")
        } else {

            MyManager.component.inject(this)
        }
    }

Basically, I'd be happy if the injection does nothing because I can set the dependencies externally for the sake of testing.

All help appreciated. Including if you think I'm coding this wrong. I'm relatively new to Kotlin and Dagger. Thanks.

推荐答案

基本上,使用Mock,您需要这样的代码:

mockkObject(MyManager)
every { MyManager.component.someOp(...) } returns 5

Not sure I understand all the details about the injection. As you said you can disable it.

Kotlin相关问答推荐

在Kotlin Jetpack中重用下拉菜单

如何创建一个空的kotlin工作?

如何定义一个函数来接受任何具有特定字段的数据类

使函数同时挂起和取消挂起

如何使用multiset与JOOQ获取关联的记录列表?

Kotlin中反射中Int到可空Double的隐式转换失败

找不到有效的 Docker 环境

如何在 jOOQ 中两次加入同一张表?

使用 Discord4j 交叉发布 Discord 消息

KMM:编译失败:意外的 IrType 类型:KIND_NOT_SET

如何在 Kotlin 中使用具有继承的泛型

.indices 在 kotlin 中的含义是什么?

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

为什么 Kotlin 需要函数引用语法?

无法从 XML 访问 NavHostFragment

DatabaseManager_Impl 不是抽象的,不会覆盖 RoomDatabase 中的抽象方法 clearAllTables()

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

使用 clear() 删除 EncryptedSharedPreferences 不起作用

使用导航组件在不同的图形之间导航

Kotlin中默认导入哪些包/函数?