BottomNavigationViewのテスト
以前の記事でBottomNavigationViewについて書きましたが、今日はそのテストについて書きます。 blog.techium.jp
BottomNavigationのメニューをクリックして、選択状態をチェックするコードを書いていきます。
パスしないテスト
@Test public void selectBottomNavigation() throws Exception { onView(withId(R.id.navigation_home)).perform(click()); onView(withId(R.id.navigation_home)).check(matches(isSelected())); }
R.id.navigation_homeのIDが付与されたメニューをクリックして、そのメニューが選択されいることを確認するコードです。
では実行してみましょう。
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'is selected' doesn't match the selected view. Expected: is selected Got: "BottomNavigationItemView{id=2131230817, res-name=navigation_home, visibility=VISIBLE, width=360, height=147, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=android.view.ViewGroup$LayoutParams@b0ee227, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}"
どうやら、クリックしたメニューは選択状態ではないようです。 View#isSelectedはfalseのようですので、別の方法で選択状態を保持しているようです。 ButtomNavigationItemViewの選択状態がどのように保持されているのか確認してみましょう。
BottomNavigationItemViewクラスについて
実際のソースコードは以下を参照
design/src/android/support/design/internal/BottomNavigationItemView.java - platform/frameworks/support.git - Git at Google
これをみると、メンバー変数のMenuItemImplクラスに選択状態が保持されており、BottomNavigationItemView#getItemDataというインターフェースにて取得できます。
MenuItemImpl#isCheckedにて選択状態が取得できます。
以上のことを踏まえてCustomMatcherを作成してみましょう。
修正後のテスト
@Test public void selectBottomNavigation() throws Exception { onView(withId(R.id.navigation_home)).perform(click()); onView(withId(R.id.navigation_home)).check(matches(isBottomNavigationItemChecked())); } public static Matcher<View> isBottomNavigationItemChecked() { return new BoundedMatcher<View, BottomNavigationItemView>(BottomNavigationItemView.class) { @Override public void describeTo(Description description) { description.appendText("with BottomNavigationItemChecked: "; } @Override protected boolean matchesSafely(BottomNavigationItemView item) { return item.getItemData().isChecked(); } }; }
これで、テスト実行するとテストが通りました。
以上です。