Koin DI Android单元测试ViewModel

问题描述

我在应用程序中使用了Koin DI,一切正常。我已经注入了viewmodels,没有问题。

例如,我有一个具有功能的calcviewmodel:

class Calcviewmodel(): viewmodel() {
    fun calculateNumber(): Int{
        var a = 5 + 3
        return a
    }
}

在应用程序中,我像这样使用它:

class Application : Application() {
    override fun onCreate() {
        super.onCreate()

        startKoin {
        // androidContext(this@MyApp)
        androidLogger(Level.DEBUG)
        androidContext(this@Application)
        modules(
            listof(
                myModule
            )
        )
    }

在我的appModule文件中:

val myModule= module {
    viewmodel { Calcviewmodel() }
}

在应用程序中,每当我需要viewmodel实例时,都只需使用:

private val calcviewmodel by viewmodel<Calcviewmodel>()

正如我所说,一切都很好,但是当我尝试为此功能编写一个简单的单元测试

fun calculateNumber(): Int{
        var a = 5 + 3
        return a
}

从视图模型中我有空指针。

这是我尝试过的测试班

class CalcviewmodelTest: KoinTest{

val calcviewmodel:Calcviewmodel by inject()

@Before
fun setup() {

    startKoin {
        module { single { myModule} }
      
    }
}

@Test
fun calculateNumber(){
    val result = calcviewmodel.calculateNumber()  // here I get that error when trying to access calcviewmodel var
    Assert.assertEquals(result,8)
}

@After
fun tearDown() {
    stopKoin()
}

}

每次尝试运行单元测试时,都会出现此错误

org.koin.core.error.NoBeanDefFoundException: No deFinition found for 
class:'com.package.Calcviewmodel'. Check your deFinitions!

同样,如果我使用相同的方法在测试类中(例如在应用程序中)获取viewmodel:

val calcviewmodel by viewmodel<Calcviewmodel>()

它使用不同的构造函数,要求3个参数(类,所有者,范围)

我也导入了gradle:

testImplementation "org.koin:koin-androidx-viewmodel:$koin_version"
testImplementation "org.koin:koin-test:$koin_version"

有人尝试过使用Koin并使用viewmodels编写单元测试吗?

谢谢

解决方法

最后,我只是初始化了viewModel并使用了实例。

 private lateinit var viewModel: CalcViewModel

以及稍后在setUp()

viewModel = CalcViewModel()