gpt4 book ai didi

android - 如何对 Paging 3(PagingSource) 进行单元测试?

转载 作者:行者123 更新时间:2023-12-03 13:25:30 27 4
gpt4 key购买 nike

谷歌最近宣布了新的 Paging 3 库、Kotlin-first 库、支持协程和 Flow 等。

我玩过codelab他们提供但似乎还没有任何测试支持,我还检查了documentation .他们没有提到任何关于测试的内容,所以例如我想对这个 PagingSource 进行单元测试:

 class GithubPagingSource(private val service: GithubService,
private val query: String) : PagingSource<Int, Repo>() {

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
//params.key is null in loading first page in that case we would use constant GITHUB_STARTING_PAGE_INDEX
val position = params.key ?: GITHUB_STARTING_PAGE_INDEX
val apiQuery = query + IN_QUALIFIER
return try {
val response = service.searchRepos(apiQuery, position, params.loadSize)
val data = response.items
LoadResult.Page(
data,
if (position == GITHUB_STARTING_PAGE_INDEX) null else position - 1,
if (data.isEmpty()) null else position + 1)
}catch (IOEx: IOException){
Log.d("GithubPagingSource", "Failed to load pages, IO Exception: ${IOEx.message}")
LoadResult.Error(IOEx)
}catch (httpEx: HttpException){
Log.d("GithubPagingSource", "Failed to load pages, http Exception code: ${httpEx.code()}")
LoadResult.Error(httpEx)
}
}
}

那么,我该如何测试,有人可以帮助我吗?

最佳答案

我目前有类似的经历,发现分页库并不是真正设计为可测试的。我敢肯定,一旦它成为一个更成熟的库,Google 会使其更具可测试性。
我能够为 PagingSource 编写测试.我使用了 RxJava 3 插件和 mockito-kotlin ,但测试的总体思路应该可以在协程版本的 API 和大多数测试框架中重现。

class ItemPagingSourceTest {

private val itemList = listOf(
Item(id = "1"),
Item(id = "2"),
Item(id = "3")
)

private lateinit var source: ItemPagingSource

private val service: ItemService = mock()

@Before
fun `set up`() {
source = ItemPagingSource(service)
}

@Test
fun `getItems - should delegate to service`() {
val onSuccess: Consumer<LoadResult<Int, Item>> = mock()
val onError: Consumer<Throwable> = mock()
val params: LoadParams<Int> = mock()

whenever(service.getItems(1)).thenReturn(Single.just(itemList))
source.loadSingle(params).subscribe(onSuccess, onError)

verify(service).getItems(1)
verify(onSuccess).accept(LoadResult.Page(itemList, null, 2))
verifyZeroInteractions(onError)
}
}
它并不完美,因为 verify(onSuccess).accept(LoadResult.Page(itemList, null, 2))依赖 LoadResult.Page成为 data class ,可以通过其属性的值进行比较。但它确实测试了 PagingSource .

关于android - 如何对 Paging 3(PagingSource) 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62473716/

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