【发布时间】:2020-10-11 18:18:14
【问题描述】:
我正在学习使用 Espresso 进行 UI 测试。我想测试将回收器视图滚动到底部,然后从视图模型加载下一页并将其传递给回收器视图。
我的片段中有以下 onScrollListener:
private fun setupOnScrollListener() {
recyclerViewApi.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val isRecyclerViewBottom = !recyclerView.canScrollVertically(1) &&
newState == RecyclerView.SCROLL_STATE_IDLE
if (isRecyclerViewBottom) {
downloadNextPage()
}
}
})
}
private fun downloadNextPage() {
showProgressBar(true)
viewModel.getNextMovies()
}
当我使用 Log.d() 手动测试它时,效果很好。
我的问题是:如何使用 Espresso(或者可能是不同的 API,如果您比 Espresso 更了解)将回收站视图滚动到此状态:
isRecyclerViewBottom = !recyclerView.canScrollVertically(1) && newState == RecyclerView.SCROLL_STATE_IDLE,
所以我的downloadNextPage() 将被调用,测试函数将提取更多数据。
我的测试功能:
@Test
fun scrollToBottom_isNextPageLoaded(){
every { repository.getApiMovies(any(), any()) } returns
Flowable.just(Resource.success(moviesList1_5)) andThen
Flowable.just(Resource.success(moviesList1_10))
val scenario = launchFragmentInContainer<ApiFragment>(factory = fragmentsFactory)
//first 5 items are in view, so I go to the last item (index 4)
recyclerView.perform(scrollToPosition<ViewHolder>(4))
recyclerView.perform(swipeDown())
//Below doesn't make any difference
Thread.sleep(1000L)
verify(exactly = 2) { repo.getApiMovies(any(), any()) }
}
我使用 Robolectric、Mockk、Espresso。我这里mock了repository类,传给ViewModelFactory的构造函数,传给ApiFragment的构造函数。
来自 JUnit 的消息:
java.lang.AssertionError: Verification failed: call 1 of 1: ApiRepository(repo#4).getApiMovies(any(), any())).
One matching call found, but needs at least 2 and at most 2 calls
Call: ApiRepository(repo#4).getApiMovies(Top Rated, 1)
这不是我的第一个测试功能。其他一切都很好。我只是不知道如何让 Espresso 进入回收站视图的底部并“拉起”它的底部边缘以调用 downloadNextPage()
【问题讨论】:
-
这能回答你的问题吗? Espresso Recyclerview scroll to end
-
@agoff,我看到了。它没有帮助,但下面我已经为它放置了我的解决方案。也许我应该把它写在这里,在 cmets 中,以使它对这个线程更加可见。
标签: android android-recyclerview android-espresso ui-testing