2016-03-31 8 views
5

私はYT Advanced Android Espressoで素晴らしいインストゥルメンタルテストのチュートリアルを見つけました。私はそこからコードを取り出し、自分のニーズに少しずつ調整しました。アンドロイド機器テストでツールバーのタイトルを確認するにはどうすればよいですか?

import static android.support.test.InstrumentationRegistry.getInstrumentation; 
import static android.support.test.espresso.Espresso.onView; 
import static android.support.test.espresso.action.ViewActions.click; 
import static android.support.test.espresso.assertion.ViewAssertions.matches; 
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom; 
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; 
import static android.support.test.espresso.matcher.ViewMatchers.withChild; 
import static android.support.test.espresso.matcher.ViewMatchers.withId; 
import static android.support.test.espresso.matcher.ViewMatchers.withParent; 
import static android.support.test.espresso.matcher.ViewMatchers.withText; 
import static org.hamcrest.core.AllOf.allOf; 

... 

@Test 
public void checkToolbarTitle() { 
    String toolbarTitile = getInstrumentation().getTargetContext().getString(R.string.my_bus_stops); 
    onView(allOf(isAssignableFrom(TextView.class), withParent(isAssignableFrom(Toolbar.class)))).check(matches(withText(toolbarTitile))); 
} 

不幸にも私にとってはうまくいきません。テストに失敗しました:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (is assignable from class: class android.widget.TextView and has parent matching: is assignable from class: class android.widget.Toolbar) 

何が問題ですか?どうすれば他の方法でテストできますか?

答えて

3

SOLUTION

方法で結構です。 Chiu-Ki Chanがチュートリアルで書いたように、あなたは「特定の1つのビューを特定する」ことができます。 しかし、あなたは適切なツールバーをインポートしたことを確認する必要があります。

import android.support.v7.widget.Toolbar; 

の代わり:

import android.widget.Toolbar; 
15

これが私の作品:

onView(allOf(instanceOf(TextView.class), withParent(withId(R.id.toolbar)))) 
    .check(matches(withText("toolbarTitile"))); 
+2

これは私には役に立たなかった。 Grzegorz Bielanskiが投稿したのは輸入だった。 instanceOfを解決できませんでした。 –

+0

なぜあなたはダウン投票ですか?ほとんどの場合(票の量を参照してください)、それがあなたにとってうまくいかないという事実は、この答えが間違っているわけではありません。 – denys

+0

「ほとんどの場合」がどのように機能するのか私の経験では、Android上で動作するものはバージョンごとに変更され、今日の関連する回答は明日には関係がないとのことです。 –

1

私ならば、私は覚えていませんこれを自分で書いたり、どこかで見つけたらツールバーのタイトルを確認する方法です:

public static Matcher<View> withToolbarTitle(CharSequence title) { 
    return withToolbarTitle(is(title)); 
} 

public static Matcher<View> withToolbarTitle(final Matcher<CharSequence> textMatcher) { 
    return new BoundedMatcher<View, Toolbar>(Toolbar.class) { 
     @Override 
     public boolean matchesSafely(Toolbar toolbar) { 
      return textMatcher.matches(toolbar.getTitle()); 
     } 

     @Override 
     public void describeTo(Description description) { 
      description.appendText("with toolbar title: "); 
      textMatcher.describeTo(description); 
     } 
    }; 
} 

これはすべてのケースで機能します。例アサーション:onView(withId(R.id.toolbar)).check(matches(withToolbarTitle("title")));

関連する問題