简体   繁体   English

如何在 viewModel 中测试从存储库返回 LiveData 值的方法

[英]How to test a method in viewModel which returns LiveData value from repository

In my ViewModel I am calling a method from my repository class which returns a LiveData from a webservice.在我的 ViewModel 中,我正在从我的存储库类中调用一个方法,该方法从 Web 服务返回一个 LiveData。 My viewModel code:我的视图模型代码:

class MainViewModel @Inject constructor(val mainRepository: MainRepository) : ViewModel() {
   val source: LiveData<My_Result> = mainRepository.fetchApiresultFromClient(str_query)  
       .......... }

My question is that is there a way to get real data from the webservice called in repository or do I just prepare the result and assert that its not null;我的问题是有没有办法从存储库中调用的 web 服务中获取真实数据,或者我是否只准备结果并断言它不为空; something like below:像下面这样:

when(mainrepository.fetchApiresultFromClient(any(String::class))).thenReturn(myPreparedLiveData<My_result>)

As the question is tagged as unit-testing, IMHO, expecting real data from a web service does not actually fall into the scope of unit-testing.由于问题被标记为单元测试,恕我直言,期望来自 Web 服务的真实数据实际上并不属于单元测试的范围。 You might call than an integration testing, however, from the unit-testing point of view, you might consider mocking the response from the function that calls the web service and verify if the method was called using proper arguments that you expect.您可能会调用集成测试,但是,从单元测试的角度来看,您可能会考虑模拟来自调用 Web 服务的函数的响应,并验证是否使用您期望的正确参数调用了该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用存储库模式和 LiveData 对 ViewModel 进行单元测试 - Unit test ViewModel using repository pattern and LiveData 如何通过 ViewModel 从 Fragment 观察 Repository LiveData - How to observe Repository LiveData from Fragment via ViewModel 无法通过 onDateSet 方法为视图模型中的 livedata 赋值 - Cant assign value to livedata in viewmodel from onDateSet method 在没有 LiveData 的情况下将数据从 Repository 返回到 ViewModel - Return data from Repository to ViewModel without LiveData 从ViewModel观察存储库LiveData并通知UI - Observing repository LiveData from ViewModel and notify UI ViewModel中的LiveData如何使用转换观察存储库中的Livedata? - How can LiveData in ViewModel observe the Livedata in Repository using Transformations? 如何使用 Kotest 和 Mockk 库为返回 LiveData 的方法编写单元测试 - How to write unit test for the method returns LiveData with Kotest and Mockk library 通过单元测试如何测试 viewModel 中的 switchMap 从存储库类调用正确的方法 - With unit testing how to test a switchMap in viewModel calls the proper method from repository class 如何从存储库返回 LiveData - How to Return LiveData from Repository 如何将 editText 值传递给 viewModel 和 Livedata (Kotlin) - How to pass editText value to viewModel and Livedata (Kotlin)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM