代码之家  ›  专栏  ›  技术社区  ›  the_new_mr

Kotlin单元测试-如何模拟伴生对象的组件?

  •  2
  • the_new_mr  · 技术社区  · 8 年前

    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
        }
    }
    

    当单元测试时,我究竟如何模拟伴生对象中的组件?

    CUT(正在测试的类)是另一个使用MyManager组件在其init块中注入依赖项的类,如下所示:

    init {
            if(applicationContext == null) {
                throw IllegalStateException("Application Context must not be null")
            } else {
    
                MyManager.component.inject(this)
            }
        }
    

    基本上,如果注入什么也不做,我会很高兴,因为为了测试,我可以在外部设置依赖项。

    感谢大家的帮助。包括如果你认为我编码错了。我对寇特林和匕首比较陌生。谢谢。

    1 回复  |  直到 8 年前
        1
  •  4
  •   oleksiyp    8 年前

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

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

    我不太清楚注射的细节。正如你所说,你可以禁用它。

    推荐文章