使用实时数据,协程(Kotlin)测试视图模型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用实时数据,协程(Kotlin)测试视图模型相关的知识,希望对你有一定的参考价值。
几天来我一直在尝试测试我的视图模型,但没有成功。
这是我的视图模型:
class AdvertViewModel : ViewModel()
private val parentJob = Job()
private val coroutineContext: CoroutineContext
get() = parentJob + Dispatchers.Default
private val scope = CoroutineScope(coroutineContext)
private val repository : AdvertRepository = AdvertRepository(ApiFactory.Apifactory.advertService)
val advertContactLiveData = MutableLiveData<String>()
fun fetchRequestContact(requestContact: RequestContact)
scope.launch
val advertContact = repository.requestContact(requestContact)
advertContactLiveData.postValue(advertContact)
这是我的存储库:
class AdvertRepository (private val api : AdvertService) : BaseRepository()
suspend fun requestContact(requestContact: RequestContact) : String?
val advertResponse = safeApiCall(
call = api.requestContact(requestContact).await(),
errorMessage = "Error Request Contact"
)
return advertResponse
这是我的视图模型测试:
@RunWith(JUnit4::class)
class AdvertViewModelTest
private val goodContact = RequestContact(...)
private lateinit var advertViewModel: AdvertViewModel
private var observer: Observer<String> = mock()
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp()
advertViewModel = AdvertViewModel()
advertViewModel.advertContactLiveData.observeForever(observer)
@Test
fun fetchRequestContact_goodResponse()
advertViewModel.fetchRequestContact(goodContact)
val captor = ArgumentCaptor.forClass(String::class.java)
captor.run
verify(observer, times(1)).onChanged(capture())
assertEquals("someValue", value)
模拟方法():
inline fun <reified T> mock(): T = Mockito.mock(T::class.java)
我遇到此错误:
想要但不被调用:observer.onChanged();-> com.vizzit.AdvertViewModelTest.fetchRequestContact_goodResponse(AdvertViewModelTest.kt:52)实际上,与该模拟游戏的互动为零。
我不知道如何检索查询结果。
答案
您需要写一个OneTimeObserver
来观察ViewModel
中的实时数据>
class OneTimeObserver<T>(private val handler: (T) -> Unit) : Observer<T>, LifecycleOwner private val lifecycle = LifecycleRegistry(this) init lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) override fun getLifecycle(): Lifecycle = lifecycle override fun onChanged(t: T) handler(t) lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
之后您可以编写扩展功能:
fun <T> LiveData<T>.observeOnce(onChangeHandler: (T) -> Unit) val observer = OneTimeObserver(handler = onChangeHandler) observe(observer, observer)
比您可以检查我从项目中获得的this
ViewModel
class类,以在调用方法时(何时)检查ViewModel
的情况。
关于您的错误,它只是说LiveData
方法从未被调用。
以上是关于使用实时数据,协程(Kotlin)测试视图模型的主要内容,如果未能解决你的问题,请参考以下文章