问题描述
我一直在使用Google的Arch库,但是使测试变得困难的一件事是使用 PagedList
。
I have been working with the arch libraries from Google, but one thing that has made testing difficult is working with PagedList
.
对于此示例,我正在使用存储库模式,并从API或网络返回详细信息。
For this example, I am using the repository pattern and returning details from either an API or network.
因此在ViewModel中,我对此接口方法进行了调用:
So within the ViewModel I make a call to this interface method:
override fun getFoos(): Observable<PagedList<Foo>>
然后,存储库将使用 RxPagedListBuilder
创建PagedList类型的 Observable
:
The Repository will then use RxPagedListBuilder
to create the Observable
that is of type PagedList:
override fun getFoos(): Observable<PagedList<Foo>> =
RxPagedListBuilder(database.fooDao().selectAll(), PAGED_LIST_CONFIG).buildObservable()
我希望能够通过测试来设置这些返回 PagedList< Foo>
的方法的返回值。类似于
I want to be able for tests to setup the return from these methods that return a PagedList<Foo>
. Something similar to
when(repository.getFoos()).thenReturn(Observable.just(TEST_PAGED_LIST_OF_FOOS)
两个问题:
- 这是
- 如何创建
PagedList< Foo>
?
- Is this possible?
- How do I create a
PagedList<Foo>
?
我的目标是以一种更端到端的方式进行验证(例如,确保在屏幕上显示正确的Foos列表)。
My goal is to verify in a more end-to-end fashion (such as ensuring that the correct list of Foos is displayed on the screen). The fragment/activity/view is the one observing the PagedList<Foo>
from a ViewModel.
推荐答案
一种简单的方法,即可通过ViewModel中的 PagedList< Foo>
要实现此目的,就是模拟PagedList。这种乐趣是将列表转换为PagedList(在这种情况下,如果您需要实现PagedList的其他方法,我们将不使用真正的PagedList,而只是使用模拟版本),
an easy way to achieve this, is to mock the PagedList. This fun will "convert" a list to a PagedList (in this case, we are not using the real PagedList rather just a mocked version, if you need other methods of PagedList to be implemented, add them in this fun)
fun <T> mockPagedList(list: List<T>): PagedList<T> {
val pagedList = Mockito.mock(PagedList::class.java) as PagedList<T>
Mockito.`when`(pagedList.get(ArgumentMatchers.anyInt())).then { invocation ->
val index = invocation.arguments.first() as Int
list[index]
}
Mockito.`when`(pagedList.size).thenReturn(list.size)
return pagedList
}
这篇关于如何为测试创建对象的PagedList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!