简体   繁体   English

Android espresso匹配视图在RecyclerView中重复

[英]Android espresso match view duplicated inside RecyclerView

I have a recycler view with the following layout: 我有一个具有以下布局的回收者视图:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/color_primary"/>

</RelativeLayout>

I have a problem because during a test I have a moment where the recycler view show two views with the same text and I need to check if one of them is visible. 我有一个问题,因为在测试过程中,我有一会儿在回收者视图中显示两个具有相同文本的视图,我需要检查其中一个是否可见。

The code to match the view is the following: 匹配视图的代码如下:

onView(withId(R.id.title)).check(matches(withText("Test")));

And espresso is failing because it is finding more than one view that matchs the matcher criteria. 浓缩咖啡之所以失败,是因为它发现了多个符合匹配标准的视图。

How can I match the specific view that I need? 如何匹配所需的特定视图?

One possible solution is to set a different tag in each row and use this tag to match with espresso. 一种可能的解决方案是在每行中设置一个不同的标签,然后使用此标签与espresso匹配。

Let's say the data that is being shown is persisted in the database. 假设正在显示的数据保留在数据库中。 You can use the model id as the tag, with this you will have each row in the recycler view with a unique constraint that you can use in the matcher. 您可以将模型ID用作标签,这样,您将使回收器视图中的每一行都有唯一的约束,您可以在匹配器中使用该约束。

The code would be something like this: 该代码将是这样的:

onView(allOf(
            withId(R.id.title),
            allOf(
                isDescendantOfA(withTagValue(is((Object)model.getId())))),
                withText(model.getTitle())))
       .check(matches(isDisplayed()))

Since you need to use the text inside the matcher, you can check if the view is visible to add a clause to your test. 由于您需要使用匹配器中的文本,因此可以检查视图是否可见,以便将子句添加到测试中。

You can read an article explaining this here: https://medium.com/tech-track/validating-views-by-tag-with-espresso-50d3f47b14a7 您可以在此处阅读说明此内容的文章: https : //medium.com/tech-track/validating-views-by-tag-with-espresso-50d3f47b14a7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM