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个参数(类、所有者、范围(

我还进口了渐变:

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

有人尝试过用Koin和viewModels编写单元测试吗?

感谢

基于Koin文档,您需要使用by inject()来创建类的实例。

val calcViewModel by inject<CalcViewModel>()

然后,像这样创建koinTestRule

@get:Rule
val koinTestRule = KoinTestRule.create {
printLogger()
modules(myModule)
}

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

private lateinit var viewModel: CalcViewModel

以及稍后在setUp((中

viewModel = CalcViewModel()

最新更新