2016-03-31 25 views
5

我在YT Advanced Android Espresso上發現了很棒的器械測試教程。我從那裏進行了代碼調整,以適應我的需求。如何查看android樂器測試中的工具欄標題?

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在她的教程中寫的,你可以「精確地指出一個特定的觀點」。 但你必須確保你正確輸入工具欄:中

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")));