英文:
How to check if recyclerView is empty Espresso
问题
如何使用 Espresso 检查我的 RecyclerView 是否为空?
我知道我可以通过点击元素位置来检查它是否有元素,但我想从检查它是否为空开始我的测试。
```kotlin
@RunWith(AndroidJUnit4ClassRunner::class)
class TagsFragmentTest {
@Rule
@JvmField
var repeatRule: RepeatRule = RepeatRule()
@get:Rule
var activityScenarioRule = activityScenarioRule<LoginActivity>()
@Test
@RepeatTest(1)
fun test_checkTags() {
// 检查主活动
Thread.sleep(5000)
onView(withId(R.id.mainFragmentManager)).check(matches(isDisplayed()))
// 转到标签片段
onView(withId(R.id.nav_tags)).check(matches(isDisplayed()))
onView(withId(R.id.nav_tags)).perform(click())
// 检查我的 RecyclerView 是否为空
// 添加标签
// 检查是否有标签
}
}
<details>
<summary>英文:</summary>
How can I check if my recyclerview is empty using espresso?
I know I can check if it has elements by clicking on element position but I want start my test by checking if it is empty.
@RunWith(AndroidJUnit4ClassRunner::class)
class TagsFragmentTest {
@Rule
@JvmField
var repeatRule: RepeatRule = RepeatRule()
@get:Rule
var activityScenarioRule = activityScenarioRule<LoginActivity>()
@Test
@RepeatTest(1)
fun test_checkTags() {
//check main activity
Thread.sleep(5000);
onView(withId(R.id.mainFragmentManager)).check(matches(isDisplayed()))
//go to Tags fragment
onView(withId(R.id.nav_tags)).check(matches(isDisplayed()))
onView(withId(R.id.nav_tags)).perform(click())
//CHECK MY RECYCLERVIEW IS EMPTY
//ADD TAGS
//CHECK IF HAS TAGS
}
}
</details>
# 答案1
**得分**: 4
我创建了一个自定义的ViewMatcher:
```kotlin
fun recyclerViewSizeMatcher(matcherSize: Int): Matcher<View?>? {
return object : BoundedMatcher<View?, RecyclerView>(RecyclerView::class.java) {
override fun describeTo(description: Description) {
description.appendText("列表大小为: $matcherSize")
}
override fun matchesSafely(recyclerView: RecyclerView): Boolean {
return matcherSize == recyclerView.adapter!!.itemCount
}
}
}
该自定义ViewMatcher用于检查adapter.itemCount
是否与传递的元素数量相符。
你可以这样使用它:
recyclerViewSizeMatcher(0)
在这种情况下,它必须为空(0个元素)。
英文:
I created a custom ViewMatcher:
fun recyclerViewSizeMatcher(matcherSize: Int): Matcher<View?>? {
return object : BoundedMatcher<View?, RecyclerView>(RecyclerView::class.java) {
override fun describeTo(description: Description) {
description.appendText("with list size: $matcherSize")
}
override fun matchesSafely(recyclerView: RecyclerView): Boolean {
return matcherSize == recyclerView.adapter!!.itemCount
}
}
}
that checks if the adapter.itemCount
has the passed elements.
You could use it as:
recyclerViewSizeMatcher(0)
in that case it has to be empty (0 elements).
答案2
得分: 0
你可以使用 https://github.com/AdevintaSpain/Barista 库,然后使用类似这样的代码:
assertListItemCount(R.id.list, 0)
英文:
You could use https://github.com/AdevintaSpain/Barista library, and then use something like this:
assertListItemCount(R.id.list, 0)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论