如何为测试创建对象的PagedList?

时间:2018-05-20 14:22:13

标签: android android-architecture-components android-paging

我一直在使用Google的拱库,但是使测试变得困难的一件事就是使用PagedList

对于此示例,我使用存储库模式并从API或网络返回详细信息。

因此,在ViewModel中,我调用了这个接口方法:

override fun getFoos(): Observable<PagedList<Foo>>

然后,存储库将使用RxPagedListBuilder创建类型为PagedList的Observable

 override fun getFoos(): Observable<PagedList<Foo>> =
            RxPagedListBuilder(database.fooDao().selectAll(), PAGED_LIST_CONFIG).buildObservable()

我希望测试可以从这些返回PagedList<Foo>的方法设置返回值。类似于

的东西
when(repository.getFoos()).thenReturn(Observable.just(TEST_PAGED_LIST_OF_FOOS)

两个问题:

  1. 这可能吗?
  2. 如何创建PagedList<Foo>
  3. 我的目标是以更加端到端的方式进行验证(例如确保在屏幕上显示正确的Foos列表)。片段/活动/视图是从ViewModel观察PagedList<Foo>的那个。

3 个答案:

答案 0 :(得分:4)

实现此目的的一种简单方法是模拟PagedList。这种有趣的操作会将列表“转换”为PagedList(在这种情况下,我们使用的不是真正的PagedList,而只是模拟版本,如果需要实现PagedList的其他方法,请在此方法中添加它们)

 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
 }

答案 1 :(得分:0)

  1. 您不能将List转换为PagedList。
  2. 您不能仅通过DataSource直接创建PagedList。一种方法是创建返回测试数据的FakeDataSource。

如果这是一个端到端测试,则可以只使用内存数据库。在调用之前添加测试数据。例: https://medium.com/exploring-android/android-architecture-components-testing-your-room-dao-classes-e06e1c9a1535

答案 2 :(得分:0)

使用模拟DataSource.Factory将列表转换为PagedList

@saied89在本solution期中共享了此googlesamples/android-architecture-components。我已经在Coinverse Open App中实现了模拟的PagedList,以便使用Kotlin,JUnit 5,MockK和AssertJ库对ViewModel进行本地单元测试。

要观察PagedList中的LiveData,我在Google的Android体系结构组件示例下使用了Jose Alcérreca'sgetOrAwaitValue中的implementation LiveDataSample sample app

asPagedList扩展功能在下面的示例测试 ContentViewModelTest.kt 中实现。

PagedListTestUtil.kt


    import android.database.Cursor
    import androidx.paging.DataSource
    import androidx.paging.LivePagedListBuilder
    import androidx.paging.PagedList
    import androidx.room.RoomDatabase
    import androidx.room.RoomSQLiteQuery
    import androidx.room.paging.LimitOffsetDataSource
    import io.mockk.every
    import io.mockk.mockk

    fun <T> List<T>.asPagedList() = LivePagedListBuilder<Int, T>(createMockDataSourceFactory(this),
        Config(enablePlaceholders = false,
                prefetchDistance = 24,
                pageSize = if (size == 0) 1 else size))
        .build().getOrAwaitValue()

    private fun <T> createMockDataSourceFactory(itemList: List<T>): DataSource.Factory<Int, T> =
        object : DataSource.Factory<Int, T>() {
            override fun create(): DataSource<Int, T> = MockLimitDataSource(itemList)
        }

    private val mockQuery = mockk<RoomSQLiteQuery> {
        every { sql } returns ""
    }

    private val mockDb = mockk<RoomDatabase> {
        every { invalidationTracker } returns mockk(relaxUnitFun = true)
    }

    class MockLimitDataSource<T>(private val itemList: List<T>) : LimitOffsetDataSource<T>(mockDb, mockQuery, false, null) {
        override fun convertRows(cursor: Cursor?): MutableList<T> = itemList.toMutableList()
        override fun countItems(): Int = itemList.count()
        override fun isInvalid(): Boolean = false
        override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<T>) { /* Not implemented */ }

        override fun loadRange(startPosition: Int, loadCount: Int) =
            itemList.subList(startPosition, startPosition + loadCount).toMutableList()

        override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<T>) {
            callback.onResult(itemList, 0)
        }
    }

LiveDataTestUtil.kt


    import androidx.lifecycle.LiveData
    import androidx.lifecycle.Observer
    import java.util.concurrent.CountDownLatch
    import java.util.concurrent.TimeUnit
    import java.util.concurrent.TimeoutException

    /**
     * Gets the value of a [LiveData] or waits for it to have one, with a timeout.
     *
     * Use this extension from host-side (JVM) tests. It's recommended to use it alongside
     * `InstantTaskExecutorRule` or a similar mechanism to execute tasks synchronously.
     */
    fun <T> LiveData<T>.getOrAwaitValue(
        time: Long = 2,
        timeUnit: TimeUnit = TimeUnit.SECONDS,
        afterObserve: () -> Unit = {}
    ): T {
        var data: T? = null
        val latch = CountDownLatch(1)
        val observer = object : Observer<T> {
            override fun onChanged(o: T?) {
                data = o
                latch.countDown()
                this@getOrAwaitValue.removeObserver(this)
            }
        }
        this.observeForever(observer)
        afterObserve.invoke()
        // Don't wait indefinitely if the LiveData is not set.
        if (!latch.await(time, timeUnit)) {
            this.removeObserver(observer)
            throw TimeoutException("LiveData value was never set.")
        }
        @Suppress("UNCHECKED_CAST")
        return data as T
    }

ContentViewModelTest.kt

    ...
    import androidx.paging.PagedList
    import com.google.firebase.Timestamp
    import io.mockk.*
    import org.assertj.core.api.Assertions.assertThat
    import org.junit.jupiter.api.AfterAll
    import org.junit.jupiter.api.BeforeAll
    import org.junit.jupiter.api.BeforeEach
    import org.junit.jupiter.api.Test
    import org.junit.jupiter.api.extension.ExtendWith

    @ExtendWith(InstantExecutorExtension::class)
    class ContentViewModelTest {
        val timestamp = getTimeframe(DAY)

        @BeforeAll
        fun beforeAll() {
            mockkObject(ContentRepository)
        }

        @BeforeEach
        fun beforeEach() {
            clearAllMocks()
        }

        @AfterAll
        fun afterAll() {
            unmockkAll()
        }

        @Test
        fun `Feed Load`() {
            val content = Content("85", 0.0, Enums.ContentType.NONE, Timestamp.now(), "",
                "", "", "", "", "", "", MAIN,
                0, 0.0, 0.0, 0.0, 0.0,
                0.0, 0.0, 0.0, 0.0)
            every {
                getMainFeedList(any(), any())
            } returns liveData { 
               emit(Lce.Content(
                   ContentResult.PagedListResult(
                        pagedList = liveData {emit(listOf(content).asPagedList())}, 
                        errorMessage = ""))
            }
            val contentViewModel = ContentViewModel(ContentRepository)
            contentViewModel.processEvent(ContentViewEvent.FeedLoad(MAIN, DAY, timestamp, false))
            assertThat(contentViewModel.feedViewState.getOrAwaitValue().contentList.getOrAwaitValue()[0])
                .isEqualTo(content)
            assertThat(contentViewModel.feedViewState.getOrAwaitValue().toolbar).isEqualTo(
                ToolbarState(
                        visibility = GONE,
                        titleRes = app_name,
                        isSupportActionBarEnabled = false))
            verify {
                getMainFeedList(any(), any())
            }
            confirmVerified(ContentRepository)
        }
    }

InstantExecutorExtension.kt

使用LiveData时,这对于JUnit 5是必需的,以确保Observer不在主线程上。以下是Jeroen Mols' implementation

    import androidx.arch.core.executor.ArchTaskExecutor
    import androidx.arch.core.executor.TaskExecutor
    import org.junit.jupiter.api.extension.AfterEachCallback
    import org.junit.jupiter.api.extension.BeforeEachCallback
    import org.junit.jupiter.api.extension.ExtensionContext

    class InstantExecutorExtension : BeforeEachCallback, AfterEachCallback {
        override fun beforeEach(context: ExtensionContext?) {
            ArchTaskExecutor.getInstance().setDelegate(object : TaskExecutor() {
                override fun executeOnDiskIO(runnable: Runnable) = runnable.run()
                override fun postToMainThread(runnable: Runnable) = runnable.run()
                override fun isMainThread(): Boolean = true
            })
        }

        override fun afterEach(context: ExtensionContext?) {
            ArchTaskExecutor.getInstance().setDelegate(null)
        }
    }