[英]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.