gpt4 book ai didi

android - 如何使用 Koin 对 MVVM 进行单元测试?

转载 作者:行者123 更新时间:2023-11-29 18:25:10 30 4
gpt4 key购买 nike

如何使用 Koin 对 MVVM 进行单元测试?

我已经尝试测试:link

但是,我不知道为什么我在 ViewModelTest fun getLookUpLeagueList() 中得到 error("No Data in ViewModel")

存储库

class LookUpLeagueRepository {

fun getLookUpLeague(idLeague: String): MutableLiveData<LookUpLeague> {
val lookUpLeague = MutableLiveData<LookUpLeague>()
APIService().getLookUpLeague(idLeague).enqueue(object : Callback<LookUpLeague> {
override fun onFailure(call: Call<LookUpLeague>, t: Throwable) {
d("TAG", "lookUpLeagueOnFailure ${t.localizedMessage}")
}

override fun onResponse(call: Call<LookUpLeague>, response: Response<LookUpLeague>) {
lookUpLeague.value = response.body()
}
})
return lookUpLeague
}
}

View 模型

class LookUpLeagueViewModel(private val lookUpLeagueRepository: LookUpLeagueRepository) :
ViewModel() {

var lookUpLeagueList = MutableLiveData<LookUpLeague>()

fun getLookUpLeagueList(idLeague: String) {
lookUpLeagueList = lookUpLeagueRepository.getLookUpLeague(idLeague)
}
}

模块

val lookUpLeagueModule = module {
single { LookUpLeagueRepository() }
viewModel { LookUpLeagueViewModel(get()) }
}

ViewModel 测试

class LookUpLeagueViewModelTest : KoinTest {

val lookUpLeagueViewModel: LookUpLeagueViewModel by inject()

val idLeague = "4328"

@get:Rule
val rule = InstantTaskExecutorRule()

@Mock
lateinit var observerData: Observer<LookUpLeague>

@Before
fun before() {
MockitoAnnotations.initMocks(this)
startKoin {
modules(lookUpLeagueModule)
}
}

@After
fun after() {
stopKoin()
}

@Test
fun getLookUpLeagueList() {
lookUpLeagueViewModel.lookUpLeagueList.observeForever(observerData)

lookUpLeagueViewModel.getLookUpLeagueList(idLeague)

val value = lookUpLeagueViewModel.lookUpLeagueList.value ?: error("No Data in ViewModel")

Mockito.verify(observerData).onChanged(value)
}
}

最佳答案

@Test
fun getLookUpLeagueList() {
lookUpLeagueViewModel.lookUpLeagueList.observeForever(observerData)
...
}

此时lookUpLeagueListMutableLiveData的一个实例。假设这是 MutableLiveData #1

lookUpLeagueViewModel.getLookUpLeagueList(idLeague)

执行上面的行将调用 LookUpLeagueViewModel.getLookUpLeagueList 函数。让我们来看看它的内部。

lookUpLeagueList = lookUpLeagueRepository.getLookUpLeague(idLeague)

LookUpLeagueRepository 中创建了一个全新的 MutableLiveData。这与 observerData 正在观察的那个不同。此时 lookUpLeagueViewModel.lookUpLeagueList 指的是新的 MutableLiveData #2 因为您将它重新分配给了 var lookUpLeagueList

val value = lookUpLeagueViewModel.lookUpLeagueList.value ?: error("No Data in ViewModel")

因此,您实际上是在查询 MutableLiveData #2,它是新的、未观察到的并且是空的。这就是 valuenull 的原因。与其声明为 var,不如将其声明为 val。不要重新分配变量、setValuepostValue 来传播更改。

关于android - 如何使用 Koin 对 MVVM 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59496387/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com