AndroidアプリをJUnitでテストするときの話です。
ViewPagerは中に複数のFragmentを入れることができるため、
同じView IDがそれぞれのFragmentに含まれているとき、
次のように単純にwithIdでマッチングさせようとすると、
複数のViewがヒットしてエラーが発生します。
onView(withId(R.id.recycler_view))
.perform(actionOnItemAtPosition(1, click()));
これを愚直に回避しようとすると次のようになります。
onView(allOf(withId(R.id.recycler_view), ViewMatchers.isDescendantOfA(Matchers.equalTo(fragment.getView())))
.perform(actionOnItemAtPosition(1, click()));
正直長くて読みづらいです。
短くするには次のようなカスタムMatcherを作ります。
public class CustomMatcher {
public static Matcher<View> withId(int id, Fragment fragment) {
return allOf(ViewMatchers.withId(id), ViewMatchers.isDescendantOfA(Matchers.equalTo(fragment.getView())));
}
}
こうすれば次のように短く書けます。
onView(withId(R.id.recycler_view, fragment))
.perform(actionOnItemAtPosition(1, click()));
テストコードは愚直に書くとグチャグチャになり可読性がカオスになることが多いので、
よく使うものは適度にカスタムMatcherを作っていくと良いでしょう。