我在我的应用程序中使用了 Koin DI,一切正常。我已经毫无问题地注入(inject)了 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
}
从 View 模型我有空指针。
这是我试过的测试类
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 编写单元测试?
谢谢
最佳答案
基于 Koin Documentation , 你需要使用 by inject()
来创建类的实例。
val calcViewModel by inject<CalcViewModel>()
然后,像这样创建koinTestRule
。
@get:Rule
val koinTestRule = KoinTestRule.create {
printLogger()
modules(myModule)
}
关于android - Koin DI Android 单元测试 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63756158/