पेजिंग लागू करने की प्रक्रिया की जांच करना

अपने ऐप्लिकेशन में Paging लाइब्रेरी को लागू करने के साथ-साथ, टेस्टिंग की एक मज़बूत रणनीति भी अपनानी चाहिए. आपको डेटा लोड करने वाले कॉम्पोनेंट, जैसे कि PagingSource और RemoteMediator की जांच करनी चाहिए, ताकि यह पक्का किया जा सके कि वे उम्मीद के मुताबिक काम कर रहे हैं. आपको एंड-टू-एंड टेस्ट भी लिखने चाहिए, ताकि यह पुष्टि की जा सके कि पेजिंग लागू करने के सभी कॉम्पोनेंट, बिना किसी खराब असर के सही तरीके से काम कर रहे हैं.

इस गाइड में, अपने ऐप्लिकेशन के अलग-अलग आर्किटेक्चर लेयर में Paging लाइब्रेरी को टेस्ट करने का तरीका बताया गया है. साथ ही, Paging लाइब्रेरी के पूरे सेटअप के लिए, एंड-टू-एंड टेस्ट लिखने का तरीका भी बताया गया है.

यूज़र इंटरफ़ेस (यूआई) लेयर टेस्ट

Compose, collectAsLazyPagingItems के ज़रिए डिक्लेरेटिव तरीके से पेजिंग डेटा का इस्तेमाल करता है. इसलिए, यूज़र इंटरफ़ेस (यूआई) लेयर के टेस्ट, मुख्य रूप से आपके ViewModel से जनरेट किए गए Flow<PagingData<Value>> पर फ़ोकस कर सकते हैं. यूज़र इंटरफ़ेस (यूआई) में मौजूद डेटा आपकी उम्मीद के मुताबिक है या नहीं, इसकी पुष्टि करने के लिए टेस्ट लिखें. इसके लिए, paging-testing डिपेंडेंसी शामिल करें. इसमें Flow<PagingData<Value>> पर asSnapshot एक्सटेंशन शामिल है. यह अपने lambda receiver में एपीआई उपलब्ध कराता है. इनकी मदद से, स्क्रोल करने वाले इंटरैक्शन को मॉक किया जा सकता है. यह स्क्रोलिंग इंटरैक्शन के मॉक से जनरेट किया गया स्टैंडर्ड List<Value> दिखाता है. इससे यह पक्का किया जा सकता है कि पेज किए जा रहे डेटा में, उन इंटरैक्शन से जनरेट किए गए ज़रूरी एलिमेंट शामिल हों. इसे यहां दिए गए स्निपेट में दिखाया गया है:

fun test_items_contain_one_to_ten() = runTest {
    // Get the Flow of PagingData from the ViewModel under test.
    val items: Flow<PagingData<String>> = viewModel.items

    val itemsSnapshot: List<String> = items.asSnapshot {
        // Scroll to the 50th item in the list. This will also suspend till
        // the prefetch requirement is met if there's one.
        // It also suspends until all loading is complete.
        scrollTo(index = 50)
    }

    // With the asSnapshot complete, you can now verify that the snapshot
    // has the expected values.
    assertEquals(
        expected = (0..50).map(Int::toString),
        actual = itemsSnapshot
    )
}

इसके अलावा, तब तक स्क्रोल किया जा सकता है, जब तक कि कोई शर्त पूरी न हो जाए. इसके बारे में यहां दिए गए स्निपेट में बताया गया है:

fun test_footer_is_visible() = runTest {
    // Get the Flow of PagingData from the ViewModel under test.
    val items: Flow<PagingData<String>> = viewModel.items

    val itemsSnapshot: List<String> = items.asSnapshot {
        // Scroll till the footer is visible.
        appendScrollWhile { item: String -> item != "Footer" }
    }
}

ट्रांसफ़ॉर्मेशन की जांच करना

आपको ऐसे यूनिट टेस्ट भी लिखने चाहिए जिनमें PagingData स्ट्रीम पर लागू किए गए सभी ट्रांसफ़ॉर्मेशन शामिल हों. asPagingSourceFactory एक्सटेंशन का इस्तेमाल करें. यह एक्सटेंशन, इस तरह के डेटा के लिए उपलब्ध है:

  • List<Value>.
  • Flow<List<Value>>.

कौनसा एक्सटेंशन इस्तेमाल करना है, यह इस बात पर निर्भर करता है कि आपको क्या टेस्ट करना है. इस्तेमाल:

  • List<Value>.asPagingSourceFactory(): अगर आपको डेटा पर map() और insertSeparators() जैसे स्टैटिक ट्रांसफ़ॉर्मेशन की जांच करनी है.
  • Flow<List<Value>>.asPagingSourceFactory(): अगर आपको यह देखना है कि आपके डेटा में किए गए अपडेट, जैसे कि बैकिंग डेटा सोर्स में लिखना, आपकी पेजिंग पाइपलाइन पर कैसे असर डालते हैं.

इनमें से किसी भी एक्सटेंशन का इस्तेमाल करने के लिए, यह पैटर्न अपनाएं:

  • अपनी ज़रूरत के हिसाब से सही एक्सटेंशन का इस्तेमाल करके, PagingSourceFactory बनाएं.
  • अपने Repository के लिए, नकली में, वापस किए गए PagingSourceFactory का इस्तेमाल करें.
  • उस Repository को अपने ViewModel को पास करें.

इसके बाद, ViewModel की जांच की जा सकती है. इसके बारे में पिछले सेक्शन में बताया गया है. इन बातों का ध्यान रखें ViewModel:

class MyViewModel(
    myRepository: MyRepository
) {
    val items = Pager(
        config = PagingConfig(pageSize = 20),
        initialKey = null,
        pagingSourceFactory = { myRepository.pagingSource() }
    )
        .flow
        .map { pagingData ->
            pagingData.insertSeparators<String, String> { before, _ ->
                when {
                    // Add a dashed String separator if the prior item is a multiple of 10.
                    before?.last() == '0' -> "---------"
                    // Return null to avoid adding a separator between two items.
                    else -> null
                }
            }
        }
}

MyViewModel में ट्रांसफ़ॉर्मेशन की जांच करने के लिए, MyRepository का एक नकली इंस्टेंस दें. यह इंस्टेंस, ट्रांसफ़ॉर्म किए जाने वाले डेटा को दिखाने वाले स्टैटिक List को डेलिगेट करता है. इसे यहां दिए गए स्निपेट में दिखाया गया है:

class FakeMyRepository() : MyRepository {
    private val items = (0..100).map(Any::toString)
    private val pagingSourceFactory = items.asPagingSourceFactory()

    // Expose as a function so a new PagingSource instance is
    // created each time it is called by the Pager.
    override fun pagingSource() = pagingSourceFactory()
}

इसके बाद, सेपरेटर लॉजिक के लिए टेस्ट लिखा जा सकता है, जैसा कि इस स्निपेट में दिखाया गया है:

fun test_separators_are_added_every_10_items() = runTest {
    // Create your ViewModel.
    val viewModel = MyViewModel(
        myRepository = FakeMyRepository()
    )
    // Get the Flow of PagingData from the ViewModel with the separator transformations applied.
    val items: Flow<PagingData<String>> = viewModel.items

    val snapshot: List<String> = items.asSnapshot()

    // With the asSnapshot complete, you can now verify that the snapshot
    // has the expected separators.
}

Compose में लोड होने की स्थितियों की जांच करना

यह टेस्ट करने के लिए कि आपके Compose यूज़र इंटरफ़ेस (यूआई) कॉम्पोनेंट, अलग-अलग लोड स्टेटस (जैसे कि LoadState.Loading या LoadState.Error) पर अलग-अलग कैसे प्रतिक्रिया देते हैं, PagingData.empty और PagingData.from का इस्तेमाल करके, MutableStateFlow के ज़रिए साफ़ तौर पर LoadStates के साथ स्टैटिक PagingData स्नैपशॉट एमिट करें:

@get:Rule
val composeTestRule = createComposeRule()

@Test
fun userListScreen_displaysLoadingDataAndErrorStates() {
  val idle = LoadState.NotLoading(endOfPaginationReached = false)
  // Emit static PagingData snapshots to test UI state transitions without a
  // Pager or ViewModel.
  val pagingDataFlow = MutableStateFlow(PagingData.empty<User>())

  composeTestRule.setContent {
    val lazyPagingItems = pagingDataFlow.collectAsLazyPagingItems()
    UserListScreen(lazyPagingItems = lazyPagingItems)
  }

  // Verify the initial loading UI before any items arrive.
  pagingDataFlow.value = PagingData.empty(
    sourceLoadStates = LoadStates(
      refresh = LoadState.Loading,
      prepend = idle,
      append = idle
    )
  )
  composeTestRule.onNodeWithTag("LoadingSpinner").assertIsDisplayed()

  // Verify that loaded items replace the loading indicator.
  pagingDataFlow.value = PagingData.from(
    data = listOf(User(id = "1", label = "User A")),
    sourceLoadStates = LoadStates(
      refresh = idle,
      prepend = idle,
      append = idle
    )
  )
  composeTestRule.onNodeWithTag("LoadingSpinner").assertIsNotDisplayed()
  composeTestRule.onNodeWithText("User A").assertIsDisplayed()

  // Verify that a refresh failure surfaces the error message in the UI.
  pagingDataFlow.value = PagingData.empty(
    sourceLoadStates = LoadStates(
      refresh = LoadState.Error(IOException("Network unavailable")),
      prepend = idle,
      append = idle
    )
  )
  composeTestRule.onNodeWithText("Network unavailable").assertIsDisplayed()
}

डेटा लेयर टेस्ट

अपने डेटा लेयर में मौजूद कॉम्पोनेंट के लिए यूनिट टेस्ट लिखें, ताकि यह पक्का किया जा सके कि वे आपके डेटा सोर्स से डेटा को सही तरीके से लोड करते हैं. डिपेंडेंसी के नकली वर्शन उपलब्ध कराएं, ताकि यह पुष्टि की जा सके कि टेस्ट किए जा रहे कॉम्पोनेंट, अलग-अलग सही तरीके से काम करते हैं. डेटा स्टोर करने की जगह की लेयर में, आपको मुख्य तौर पर PagingSource और RemoteMediator की जांच करनी होगी.

PagingSource टेस्ट

PagingSource को लागू करने के लिए यूनिट टेस्ट में, PagingSource इंस्टेंस को सेट अप करना और TestPager की मदद से उससे डेटा लोड करना शामिल है.

टेस्टिंग के लिए PagingSource इंस्टेंस सेट अप करने के लिए, कंस्ट्रक्टर को नकली डेटा दें. इससे आपको अपने टेस्ट के डेटा पर कंट्रोल मिलता है. यहां दिए गए उदाहरण में, RedditApi पैरामीटर एक Retrofit इंटरफ़ेस है. यह सर्वर के अनुरोधों और जवाब वाली क्लास को तय करता है. नकली वर्शन, इंटरफ़ेस को लागू कर सकता है, ज़रूरी फ़ंक्शन को बदल सकता है, और टेस्ट में नकली ऑब्जेक्ट के काम करने के तरीके को कॉन्फ़िगर करने के लिए आसान तरीके उपलब्ध करा सकता है.

नकली ऑब्जेक्ट सेट अप करने के बाद, डिपेंडेंसी सेट अप करें और टेस्ट में PagingSource ऑब्जेक्ट को शुरू करें. यहां दिए गए उदाहरण में, टेस्ट पोस्ट की सूची के साथ FakeRedditApi ऑब्जेक्ट को शुरू करने और RedditPagingSource इंस्टेंस की जांच करने का तरीका बताया गया है:

class SubredditPagingSourceTest {
    private val mockPosts = listOf(
        postFactory.createRedditPost(DEFAULT_SUBREDDIT),
        postFactory.createRedditPost(DEFAULT_SUBREDDIT),
        postFactory.createRedditPost(DEFAULT_SUBREDDIT)
    )
    private val fakeApi = FakeRedditApi().apply {
        mockPosts.forEach { post -> addPost(post) }
    }

    @Test
    fun loadReturnsPageWhenOnSuccessfulLoadOfItemKeyedData() = runTest {
        val pagingSource = RedditPagingSource(
            fakeApi,
            DEFAULT_SUBREDDIT
        )

        val pager = TestPager(CONFIG, pagingSource)

        val result = pager.refresh() as LoadResult.Page

        // Write assertions against the loaded data.
        assertThat(result.data)
            .containsExactlyElementsIn(mockPosts)
            .inOrder()
    }
}

TestPager की मदद से, ये काम भी किए जा सकते हैं:

  • अपने PagingSource से लगातार लोड होने वाले विज्ञापनों की जांच करें:

@Test
fun test_consecutive_loads() = runTest {

    val page = with(pager) {
        refresh()
        append()
        append()
    } as LoadResult.Page

    assertThat(page.data)
        .containsExactlyElementsIn(testPosts)
        .inOrder()
}

  • अपने PagingSource में गड़बड़ी की स्थितियों की जांच करें:

@Test
fun refresh_returnError() {
    val pagingSource = RedditPagingSource(
        fakeApi,
        DEFAULT_SUBREDDIT
    )
    // Configure your fake to return errors.
    fakeApi.setReturnsError()
    val pager = TestPager(CONFIG, source)

    runTest {
        source.errorNextLoad = true
        val result = pager.refresh()
        assertTrue(result is LoadResult.Error)

        val page = pager.getLastLoadedPage()
        assertThat(page).isNull()
    }
}

RemoteMediator टेस्ट

RemoteMediator यूनिट टेस्ट का मकसद यह पुष्टि करना है कि load() फ़ंक्शन, सही MediatorResult दिखाता है. खराब असर की जांच करने के लिए, इंटिग्रेशन टेस्ट बेहतर होते हैं. जैसे, डेटाबेस में डेटा डालने की जांच.

सबसे पहले, यह तय करें कि आपके RemoteMediator को लागू करने के लिए किन डिपेंडेंसी की ज़रूरत है. यहां दिए गए उदाहरण में, RemoteMediator को लागू करने का तरीका बताया गया है. इसके लिए, Room डेटाबेस, Retrofit इंटरफ़ेस, और खोज स्ट्रिंग की ज़रूरत होती है:

@OptIn(ExperimentalPagingApi::class)
class PageKeyedRemoteMediator(
    private val db: RedditDb,
    private val redditApi: RedditApi,
    private val subredditName: String
) : RemoteMediator<Int, RedditPost>() {
    // ...
}

PagingSource टेस्ट सेक्शन में दिखाए गए तरीके से, Retrofit इंटरफ़ेस और खोज स्ट्रिंग दी जा सकती है. Room डेटाबेस का मॉक वर्शन उपलब्ध कराना बहुत मुश्किल है. इसलिए, पूरे मॉक वर्शन के बजाय, डेटाबेस का इन-मेमोरी इंप्लिमेंटेशन उपलब्ध कराना आसान हो सकता है. Room डेटाबेस बनाने के लिए, Context ऑब्जेक्ट की ज़रूरत होती है. इसलिए, आपको इस RemoteMediator टेस्ट को androidTest डायरेक्ट्री में रखना होगा और इसे AndroidJUnit4 टेस्ट रनर के साथ चलाना होगा, ताकि इसके पास टेस्ट ऐप्लिकेशन कॉन्टेक्स्ट का ऐक्सेस हो. इंस्ट्रुमेंटेड टेस्ट के बारे में ज़्यादा जानने के लिए, इंस्ट्रुमेंटेड यूनिट टेस्ट बनाना लेख पढ़ें.

टियर-डाउन फ़ंक्शन तय करें, ताकि यह पक्का किया जा सके कि टेस्ट फ़ंक्शन के बीच स्टेट लीक न हो. इससे यह पक्का होता है कि टेस्ट रन के बीच एक जैसे नतीजे मिलें.

@ExperimentalPagingApi
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(AndroidJUnit4::class)
class PageKeyedRemoteMediatorTest {
    private val postFactory = PostFactory()
    private val mockPosts = listOf(
        postFactory.createRedditPost(SubRedditViewModel.DEFAULT_SUBREDDIT),
        postFactory.createRedditPost(SubRedditViewModel.DEFAULT_SUBREDDIT),
        postFactory.createRedditPost(SubRedditViewModel.DEFAULT_SUBREDDIT)
    )
    private val mockApi = mockRedditApi()

    private val mockDb = RedditDb.create(
        ApplicationProvider.getApplicationContext(),
        useInMemory = true
    )

    @After
    fun tearDown() {
        mockDb.clearAllTables()
        // Clear out failure message to default to the successful response.
        mockApi.failureMsg = null
        // Clear out posts after each test run.
        mockApi.clearPosts()
    }
}

अगला चरण, load() फ़ंक्शन को टेस्ट करना है. इस उदाहरण में, टेस्ट करने के लिए तीन केस हैं:

  • पहला केस तब होता है, जब mockApi मान्य डेटा दिखाता है. load() फ़ंक्शन को MediatorResult.Success दिखाना चाहिए और endOfPaginationReached प्रॉपर्टी false होनी चाहिए.
  • दूसरा मामला तब होता है, जब mockApi से सही जवाब मिलता है, लेकिन वापस किया गया डेटा खाली होता है. load() फ़ंक्शन को MediatorResult.Success दिखाना चाहिए और endOfPaginationReached प्रॉपर्टी को true दिखाना चाहिए.
  • तीसरा मामला तब होता है, जब डेटा फ़ेच करते समय mockApi कोई गड़बड़ी दिखाता है. load() फ़ंक्शन को MediatorResult.Error दिखाना चाहिए.

पहले केस की जांच करने के लिए, यह तरीका अपनाएं:

  1. वापस किए जाने वाले पोस्ट डेटा के साथ mockApi सेट अप करें.
  2. RemoteMediator ऑब्जेक्ट को शुरू करें.
  3. load() फ़ंक्शन को आज़माएं.

@Test
fun refreshLoadReturnsSuccessResultWhenMoreDataIsPresent() = runTest {
    // Add mock results for the API to return.
    mockPosts.forEach { post -> mockApi.addPost(post) }
    val remoteMediator = PageKeyedRemoteMediator(
        mockDb,
        mockApi,
        SubRedditViewModel.DEFAULT_SUBREDDIT
    )
    val pagingState = PagingState<Int, RedditPost>(
        listOf(),
        null,
        PagingConfig(10),
        10
    )
    val result = remoteMediator.load(LoadType.REFRESH, pagingState)
    assertTrue { result is MediatorResult.Success }
    assertFalse { (result as MediatorResult.Success).endOfPaginationReached }
}

दूसरे टेस्ट के लिए, mockApi को खाली नतीजा दिखाना होगा. हर टेस्ट रन के बाद, mockApi से डेटा मिटा दिया जाता है. इसलिए, डिफ़ॉल्ट रूप से यह खाली नतीजा दिखाएगा.

@Test
fun refreshLoadSuccessAndEndOfPaginationWhenNoMoreData() = runTest {
    // To test endOfPaginationReached, don't set up the mockApi to return post
    // data here.
    val remoteMediator = PageKeyedRemoteMediator(
        mockDb,
        mockApi,
        SubRedditViewModel.DEFAULT_SUBREDDIT
    )
    val pagingState = PagingState<Int, RedditPost>(
        listOf(),
        null,
        PagingConfig(10),
        10
    )
    val result = remoteMediator.load(LoadType.REFRESH, pagingState)
    assertTrue { result is MediatorResult.Success }
    assertTrue { (result as MediatorResult.Success).endOfPaginationReached }
}

आखिरी टेस्ट के लिए, mockApi को एक अपवाद दिखाना होगा, ताकि टेस्ट यह पुष्टि कर सके कि load() फ़ंक्शन, MediatorResult.Error को सही तरीके से दिखाता है.

@Test
fun refreshLoadReturnsErrorResultWhenErrorOccurs() = runTest {
    // Set up failure message to throw exception from the mock API.
    mockApi.failureMsg = "Throw test failure"
    val remoteMediator = PageKeyedRemoteMediator(
        mockDb,
        mockApi,
        SubRedditViewModel.DEFAULT_SUBREDDIT
    )
    val pagingState = PagingState<Int, RedditPost>(
        listOf(),
        null,
        PagingConfig(10),
        10
    )
    val result = remoteMediator.load(LoadType.REFRESH, pagingState)
    assertTrue { result is MediatorResult.Error }
}

शुरू से आखिर तक के टेस्ट

यूनिट टेस्ट से यह पक्का होता है कि Paging के अलग-अलग कॉम्पोनेंट, अलग-अलग काम करते हैं. हालांकि, एंड-टू-एंड टेस्ट से यह भरोसा मिलता है कि ऐप्लिकेशन पूरी तरह से काम करता है. इन टेस्ट से यह पुष्टि करने में मदद मिलती है कि आपकी डेटा लेयर (PagingSource या RemoteMediator), ViewModel, और Compose यूआई, बिना किसी अनचाहे खराब असर के आसानी से इंटिग्रेट हो जाएं. टेस्ट के लिए अब भी कुछ मॉक डिपेंडेंसी की ज़रूरत होगी. हालांकि, आम तौर पर ये आपके ऐप्लिकेशन के ज़्यादातर कोड को कवर करेंगे.

इस सेक्शन में दिए गए उदाहरण में, मॉक एपीआई डिपेंडेंसी का इस्तेमाल किया गया है, ताकि टेस्ट में नेटवर्क का इस्तेमाल न करना पड़े. मॉक एपीआई को इस तरह कॉन्फ़िगर किया गया है कि वह टेस्ट डेटा का एक जैसा सेट दिखाए. इससे टेस्ट को बार-बार किया जा सकता है. एंड-टू-एंड टेस्ट के लिए, आम तौर पर असली नेटवर्क एपीआई को नकली नेटवर्क एपीआई से बदल दिया जाता है. हालांकि, टेस्ट की विश्वसनीयता बनाए रखने के लिए, Paging लाइब्रेरी को असल फ़ेचिंग और लोकल डेटाबेस कैश मेमोरी को मैनेज करने की अनुमति दी जाती है. ऐसा तब होता है, जब RemoteMediator का इस्तेमाल किया जा रहा हो.

अपना कोड इस तरह से लिखें कि डिपेंडेंसी के मॉक वर्शन को आसानी से बदला जा सके. यहां दिए गए उदाहरण में, सर्विस लोकेटर को लागू करने के बुनियादी तरीके का इस्तेमाल किया गया है. साथ ही, मॉक एपीआई की मदद से टेस्ट सेट अप किया गया है, ताकि यह पुष्टि की जा सके कि Compose स्क्रीन, पेज पर मौजूद डेटा को सही तरीके से इस्तेमाल और दिखाती है. बड़े ऐप्लिकेशन में, Hilt जैसी डिपेंडेंसी इंजेक्शन लाइब्रेरी का इस्तेमाल करके, ज़्यादा जटिल डिपेंडेंसी ग्राफ़ को मैनेज किया जा सकता है.

टेस्ट स्ट्रक्चर सेट अप करने के बाद, अगला चरण यह पुष्टि करना है कि Pager को लागू करने से मिला डेटा सही है. एक टेस्ट से यह पुष्टि होनी चाहिए कि स्क्रीन पहली बार लोड होने पर, Compose यूज़र इंटरफ़ेस (यूआई) में सही आइटम दिखें. साथ ही, दूसरे टेस्ट से यह पुष्टि होनी चाहिए कि यूज़र इंटरफ़ेस (यूआई), उपयोगकर्ता के इंटरैक्शन के आधार पर अतिरिक्त डेटा को सही तरीके से लोड करे.

यहां दिए गए उदाहरण में, टेस्ट से यह पुष्टि की जाती है कि यूज़र इंटरफ़ेस (यूआई) में, पेज पर मौजूद डेटा सही तरीके से दिख रहा है.

// import androidx.compose.ui.test.assertIsDisplayed
// import androidx.compose.ui.test.assertDoesNotExist
// import androidx.compose.ui.test.hasText
// import androidx.compose.ui.test.junit4.v2.createComposeRule
// import androidx.compose.ui.test.onNodeWithTag
// import androidx.compose.ui.test.onNodeWithText
// import androidx.compose.ui.test.performClick
// import androidx.compose.ui.test.performTextClearance
// import androidx.compose.ui.test.performTextInput
// import androidx.test.ext.junit.runners.AndroidJUnit4
// import kotlinx.coroutines.test.runTest
// import org.junit.Before
// import org.junit.Rule
// import org.junit.Test
// import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class RedditScreenTest {

    @get:Rule
    val composeTestRule = createComposeRule()

    private val postFactory = PostFactory()
    private val mockApi = MockRedditApi()

    @Before
    fun setup() {
        // Pre-populate the mock API with test data for the default subreddit.
        mockApi.addPost(postFactory.createRedditPost(subreddit = "androiddev", title = "Jetpack Compose Paging"))

        // Swap your real dependency injection module/Service Locator with the mock API.
        ServiceLocator.swap(
            object : DefaultServiceLocator(useInMemoryDb = true) {
                override fun getRedditApi(): RedditApi = mockApi
            }
        )
    }

    @Test
    fun loadsTheDefaultResults() = runTest {
        // 1. Set the Compose UI content.
        composeTestRule.setContent {
            MyTheme {
                // Assume that this composable uses `collectAsLazyPagingItems()` internally.
                RedditScreen(initialSubreddit = "androiddev")
            }
        }

        // 2. Wait for the asynchronous Paging loads to complete.
        composeTestRule.waitUntilExactlyOneExists(
            matcher = hasText("Jetpack Compose Paging"),
            timeoutMillis = 5000
        )

        // 3. Assert that the loaded paged items are displayed correctly on screen.
        composeTestRule.onNodeWithText("Jetpack Compose Paging").assertIsDisplayed()
    }

    @Test
    fun loadsNewDataBasedOnUserInput() = runTest {
        // Add data for a different subreddit to the mock API.
        mockApi.addPost(postFactory.createRedditPost(subreddit = "compose", title = "Compose Testing"))

        composeTestRule.setContent {
            MyTheme {
                RedditScreen(initialSubreddit = "androiddev")
            }
        }

        // Wait for the initial load to finish.
        composeTestRule.waitUntilExactlyOneExists(hasText("Jetpack Compose Paging"))

        // Simulate user entering a new subreddit in a text field and clicking search.
        composeTestRule.onNodeWithTag("SubredditInput").performTextClearance()
        composeTestRule.onNodeWithTag("SubredditInput").performTextInput("compose")
        composeTestRule.onNodeWithTag("SearchButton").performClick()

        // Wait for the new paged data to load.
        composeTestRule.waitUntilExactlyOneExists(
            matcher = hasText("Compose Testing"),
            timeoutMillis = 5000
        )

        // Assert the old data is gone and the new data is displayed.
        composeTestRule.onNodeWithText("Jetpack Compose Paging").assertDoesNotExist()
        composeTestRule.onNodeWithText("Compose Testing").assertIsDisplayed()
    }
}

Flow<PagingData>, डेटा को एसिंक्रोनस तरीके से लोड करता है. इसलिए, आपको Paging लाइब्रेरी को शुरुआती लोड फ़ेच करने और उसे collectAsLazyPagingItems में भेजने के लिए समय देना होगा. इसके बाद ही, दावे किए जा सकते हैं. ऐसा करने के लिए, composeTestRule.waitUntil या waitUntilExactlyOneExists का इस्तेमाल करें, जैसा कि पिछले उदाहरण में दिखाया गया है.

डेटा लोड होने के बाद, onNodeWithText का इस्तेमाल करके, सीधे Compose के सिमैंटिक ट्री के हिसाब से दावा किया जा सकता है. इससे यह पुष्टि की जा सकती है कि आइटम असल में आपके LazyColumn में रेंडर किए गए हैं.

अन्य संसाधन

कॉन्टेंट देखना