android 如何对分页3(PagingSource)进行单元测试?

xurqigkl  于 2023-03-21  发布在  Android
关注(0)|答案(6)|浏览(181)

Google最近宣布了新的Paging 3库,Kotlin第一库,支持协同程序和流...等等。
我尝试了他们提供的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)
    }
  }
}

那么,我怎么才能测试这个,是任何人都可以帮助我??

wz8daaqr

wz8daaqr1#

我最近也有类似的经历,发现分页库并不是真的设计成可测试的,我相信Google会在它成为一个更成熟的库后使它更易于测试。
我能够为PagingSource编写一个测试,我使用了RxJava 3插件和mockito-kotlin,但是测试的总体思路应该可以用API的Coroutines版本和大多数测试框架重现。

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.Pagedata class,这可以通过它的属性值进行比较,但是它确实测试了PagingSource

bd1hkmkf

bd1hkmkf2#

使用AsyncPagingDataDiffer可以实现这一点
步骤1.创建DiffCallback

class DiffFavoriteEventCallback : DiffUtil.ItemCallback<FavoriteEventUiModel>() {
    override fun areItemsTheSame(
        oldItem: FavoriteEventUiModel,
        newItem: FavoriteEventUiModel
    ): Boolean {
        return oldItem == newItem
    }

    override fun areContentsTheSame(
        oldItem: FavoriteEventUiModel,
        newItem: FavoriteEventUiModel
    ): Boolean {
        return oldItem == newItem
    }
}

步骤2.创建ListCallback

class NoopListCallback : ListUpdateCallback {
    override fun onChanged(position: Int, count: Int, payload: Any?) {}
    override fun onMoved(fromPosition: Int, toPosition: Int) {}
    override fun onInserted(position: Int, count: Int) {}
    override fun onRemoved(position: Int, count: Int) {}
}

步骤3.向差异提交数据并进行屏幕截图

@Test
    fun WHEN_init_THEN_shouldGetEvents_AND_updateUiModel() {
        coroutineDispatcher.runBlockingTest {
            val eventList = listOf(FavoriteEvent(ID, TITLE, Date(1000), URL))
            val pagingSource = PagingData.from(eventList)

            val captureUiModel = slot<PagingData<FavoriteEventUiModel>>()
            every { uiModelObserver.onChanged(capture(captureUiModel)) } answers {}
            coEvery { getFavoriteUseCase.invoke() } returns flowOf(pagingSource)

            viewModel.uiModel.observeForever(uiModelObserver)

            val differ = AsyncPagingDataDiffer(
                diffCallback = DiffFavoriteEventCallback(),
                updateCallback = NoopListCallback(),
                workerDispatcher = Dispatchers.Main
            )

            val job = launch {
                viewModel.uiModel.observeForever {
                    runBlocking {
                        differ.submitData(it)
                    }
                }
            }

            val result = differ.snapshot().items[0]
            assertEquals(result.id, ID)
            assertEquals(result.title, TITLE)
            assertEquals(result.url, URL)

            job.cancel()

            viewModel.uiModel.removeObserver(uiModelObserver)
        }
    }

文件https://developer.android.com/reference/kotlin/androidx/paging/AsyncPagingDataDiffer

2ic8powd

2ic8powd3#

我有解决方案,但我不认为这是分页v3测试的好主意。我的分页v3的所有测试是在仪器测试上工作,而不是本地单元测试,这是因为如果我把同样的方法放在本地测试中(也用robolectrict),它仍然不起作用。
这是我的测试用例,我使用mockwebserver模拟和计算网络请求,这些请求必须与我的预期请求相等

@RunWith(AndroidJUnit4::class)
@SmallTest
class SearchMoviePagingTest {
    private lateinit var recyclerView: RecyclerView
    private val query = "A"
    private val totalPage = 4

    private val service: ApiService by lazy {
        Retrofit.Builder()
                .baseUrl("http://localhost:8080")
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(ApiService::class.java)
    }

    private val mappingCountCallHandler: HashMap<Int, Int> = HashMap<Int, Int>().apply {
        for (i in 0..totalPage) {
            this[i] = 0
        }
    }

    private val adapter: RecyclerTestAdapter<MovieItemResponse> by lazy {
        RecyclerTestAdapter()
    }

    private lateinit var pager: Flow<PagingData<MovieItemResponse>>

    private lateinit var mockWebServer: MockWebServer

    private val context: Context
        get() {
            return InstrumentationRegistry.getInstrumentation().targetContext
        }

    @Before
    fun setup() {
        mockWebServer = MockWebServer()
        mockWebServer.start(8080)

        recyclerView = RecyclerView(context)
        recyclerView.adapter = adapter

        mockWebServer.dispatcher = SearchMoviePagingDispatcher(context, ::receiveCallback)
        pager = Pager(
                config = PagingConfig(
                        pageSize = 20,
                        prefetchDistance = 3, // distance backward to get pages
                        enablePlaceholders = false,
                        initialLoadSize = 20
                ),
                pagingSourceFactory = { SearchMoviePagingSource(service, query) }
        ).flow
    }

    @After
    fun tearDown() {
        mockWebServer.dispatcher.shutdown()
        mockWebServer.shutdown()
    }

    @Test
    fun should_success_get_data_and_not_retrieve_anymore_page_if_not_reached_treshold() {
        runBlocking {
            val job = executeLaunch(this)
            delay(1000)
            adapter.forcePrefetch(10)
            delay(1000)

            Assert.assertEquals(1, mappingCountCallHandler[1])
            Assert.assertEquals(0, mappingCountCallHandler[2])
            Assert.assertEquals(20, adapter.itemCount)
            job.cancel()
        }
    }

....
    private fun executeLaunch(coroutineScope: CoroutineScope) = coroutineScope.launch {
        val res = pager.cachedIn(this)
        res.collectLatest {
            adapter.submitData(it)
        }
    }

    private fun receiveCallback(reqPage: Int) {
        val prev = mappingCountCallHandler[reqPage]!!
        mappingCountCallHandler[reqPage] = prev + 1
    }
}

请继续:)

vql8enpb

vql8enpb4#

我刚刚遇到了同样的问题,这里是answer
步骤1是创建一个模拟。

@OptIn(ExperimentalCoroutinesApi::class)
class SubredditPagingSourceTest {
  private val postFactory = PostFactory()
  private val mockPosts = listOf(
    postFactory.createRedditPost(DEFAULT_SUBREDDIT),
    postFactory.createRedditPost(DEFAULT_SUBREDDIT),
    postFactory.createRedditPost(DEFAULT_SUBREDDIT)
  )
  private val mockApi = MockRedditApi().apply {
    mockPosts.forEach { post -> addPost(post) }
  }
}

第二步是对PageSource的核心方法load方法进行单元测试:

@Test
// Since load is a suspend function, runBlockingTest is used to ensure that it
// runs on the test thread.
fun loadReturnsPageWhenOnSuccessfulLoadOfItemKeyedData() = runBlockingTest {
  val pagingSource = ItemKeyedSubredditPagingSource(mockApi, DEFAULT_SUBREDDIT)
  assertEquals(
    expected = Page(
      data = listOf(mockPosts[0], mockPosts[1]),
      prevKey = mockPosts[0].name,
      nextKey = mockPosts[1].name
    ),
    actual = pagingSource.load(
      Refresh(
        key = null,
        loadSize = 2,
        placeholdersEnabled = false
      )
    ),
  )
}
rqqzpn5f

rqqzpn5f5#

新的分页测试API刚刚发布,通过将分页的输出作为基本的List读取,使“作为状态”测试PagingSources成为可能。
主要有两种API:

  • 返回一个List<Value>
  • 返回一个() -> PagingSource<Value>

每种方法都有不同的用例。第一种方法通常用于Assert业务逻辑状态保持器的输出,通常是AAC ViewModel。第二种方法用于可以传递给ViewModelfakes,使您可以单独在UI层中对分页集成进行单元测试,而不必依赖数据层中的实际PagingSource实现。

pkmbmrz7

pkmbmrz76#

Kotlin协同程序流程

您可以在测试运行之前和之后使用JUnit本地测试和set the TestCoroutineDispatcher,然后调用PagingSource发出Kotlin流的方法,在本地测试环境中观察结果数据,并与预期进行比较。
JUnit 5测试扩展不是必需的,只需要在每次测试之前和之后设置和清除调度器,以便观察测试环境中的协同程序与Android系统上的协同程序。

@ExperimentalCoroutinesApi
class FeedViewTestExtension : BeforeEachCallback, AfterEachCallback, ParameterResolver {

    override fun beforeEach(context: ExtensionContext?) {
        // Set TestCoroutineDispatcher.
        Dispatchers.setMain(context?.root
                ?.getStore(TEST_COROUTINE_DISPATCHER_NAMESPACE)
                ?.get(TEST_COROUTINE_DISPATCHER_KEY, TestCoroutineDispatcher::class.java)!!)
    }

    override fun afterEach(context: ExtensionContext?) {
        // Reset TestCoroutineDispatcher.
        Dispatchers.resetMain()
        context?.root
                ?.getStore(TEST_COROUTINE_DISPATCHER_NAMESPACE)
                ?.get(TEST_COROUTINE_DISPATCHER_KEY, TestCoroutineDispatcher::class.java)!!
                .cleanupTestCoroutines()
        context.root
                ?.getStore(TEST_COROUTINE_SCOPE_NAMESPACE)
                ?.get(TEST_COROUTINE_SCOPE_KEY, TestCoroutineScope::class.java)!!
                .cleanupTestCoroutines()
    }

    ...
}

您可以在Coinverse sample app中的 app/src/test/java/app/coinverse/feedViewModel/FeedViewTest 下查看分页2的本地JUnit 5测试。
分页3的不同之处在于,您不需要设置LiveData执行器,因为KotlinFlow可以返回PagingData

相关问题