Android
Espresso
フラグメントやリストなど、何かと繰り返すコンテンツってありますよね?
Androidのテスト用サポートライブラリ、Espressoですが、同じ名前やIDなのに複数存在する要素をテストしようとすると、下記のエラーが出ます。
android.support.test.espresso.AmbiguousViewMatcherException: ‘with id: jp.onlineconsultant.hogehoge:id/take_over_text’ matches multiple views in the hierarchy.
Problem views are marked with ‘****MATCHES****’ below.
//ビューのxmlレイアウトファイル
<TableRow
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginTop="1dp"
android:background="#FFFFFF"
android:padding="3dp"
android:id="@+id/sender_take_over_text">
<TextView
android:id="@+id/take_over_text"
android:layout_width="0dp"
android:layout_weight="1"
android:text="@string/take_over" />
<TextView
android:id="@+id/take_over"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"></TextView>
</TableRow>
<TableRow
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginTop="1dp"
android:background="#FFFFFF"
android:padding="3dp"
android:id="@+id/sender_take_over_text">
<TextView
android:id="@+id/take_over_text"
android:layout_width="0dp"
android:layout_weight="1"
android:text="@string/take_over" />
<TextView
android:id="@+id/take_over"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"></TextView>
</TableRow>
//テストコード
onView(withId(R.id.take_over_text)).check(matches(withText(R.string.take_over)));
そういう時は、allOfを使って、親要素のIDなどを取得してどちらがどちらか、という判定を作ります。
onView(allOf(withId(R.id.take_over_text), withParent(withId(R.id.sender_take_over_text))))
.check(matches(withText(R.string.take_over)));
これでOKです!
withParentだと、直上の親の要素を指定することがあるので、おじいちゃん/おばあちゃんの要素を取りたい場合は
isDescendantOfA
を使えばOKです。