本文說明如何設定各種常見的 Espresso 測試。
比對相鄰的檢視畫面
版面配置可能包含某些本身不重複的檢視畫面。舉例來說,聯絡人表格中重複的通話按鈕可能具有相同的 R.id、包含相同的文字,且與檢視區塊階層中的其他通話按鈕具有相同的屬性。
舉例來說,在這個活動中,含有文字 "7" 的檢視畫面會在多個資料列中重複:

通常,非專屬檢視畫面會與位於其旁邊的某些專屬標籤配對,例如通話按鈕旁邊的聯絡人名稱。在這種情況下,您可以使用 hasSibling() 比對器縮小選取範圍:
Kotlin
onView(allOf(withText("7"), hasSibling(withText("item: 0")))) .perform(click())
Java
onView(allOf(withText("7"), hasSibling(withText("item: 0")))) .perform(click());
比對動作列中的檢視畫面
ActionBarTestActivity 有兩個不同的動作列:一般動作列和從選項選單建立的關聯動作列。這兩個動作列都有一個一律顯示的項目,以及兩個只在溢位選單中顯示的項目。點選項目後,TextView 會變更為所點選項目的內容。
比對兩個動作列上顯示的圖示很簡單,如以下程式碼片段所示:
Kotlin
fun testClickActionBarItem() { // We make sure the contextual action bar is hidden. onView(withId(R.id.hide_contextual_action_bar)) .perform(click()) // Click on the icon - we can find it by the r.Id. onView(withId(R.id.action_save)) .perform(click()) // Verify that we have really clicked on the icon // by checking the TextView content. onView(withId(R.id.text_action_bar_result)) .check(matches(withText("Save"))) }
Java
public void testClickActionBarItem() { // We make sure the contextual action bar is hidden. onView(withId(R.id.hide_contextual_action_bar)) .perform(click()); // Click on the icon - we can find it by the r.Id. onView(withId(R.id.action_save)) .perform(click()); // Verify that we have really clicked on the icon // by checking the TextView content. onView(withId(R.id.text_action_bar_result)) .check(matches(withText("Save"))); }

關聯動作列的程式碼看起來相同:
Kotlin
fun testClickActionModeItem() { // Make sure we show the contextual action bar. onView(withId(R.id.show_contextual_action_bar)) .perform(click()) // Click on the icon. onView((withId(R.id.action_lock))) .perform(click()) // Verify that we have really clicked on the icon // by checking the TextView content. onView(withId(R.id.text_action_bar_result)) .check(matches(withText("Lock"))) }
Java
public void testClickActionModeItem() { // Make sure we show the contextual action bar. onView(withId(R.id.show_contextual_action_bar)) .perform(click()); // Click on the icon. onView((withId(R.id.action_lock))) .perform(click()); // Verify that we have really clicked on the icon // by checking the TextView content. onView(withId(R.id.text_action_bar_result)) .check(matches(withText("Lock"))); }

在一般動作列中,點選溢位選單中的項目會比較棘手,因為部分裝置具有硬體溢位選單按鈕,可在選項選單中開啟溢位項目,而部分裝置則具有軟體溢位選單按鈕,可開啟一般溢位選單。幸好,Espresso 會為我們處理這項作業。
一般動作列:
Kotlin
fun testActionBarOverflow() { // Make sure we hide the contextual action bar. onView(withId(R.id.hide_contextual_action_bar)) .perform(click()) // Open the options menu OR open the overflow menu, depending on whether // the device has a hardware or software overflow menu button. openActionBarOverflowOrOptionsMenu( ApplicationProvider.getApplicationContext<Context>()) // Click the item. onView(withText("World")) .perform(click()) // Verify that we have really clicked on the icon by checking // the TextView content. onView(withId(R.id.text_action_bar_result)) .check(matches(withText("World"))) }
Java
public void testActionBarOverflow() { // Make sure we hide the contextual action bar. onView(withId(R.id.hide_contextual_action_bar)) .perform(click()); // Open the options menu OR open the overflow menu, depending on whether // the device has a hardware or software overflow menu button. openActionBarOverflowOrOptionsMenu( ApplicationProvider.getApplicationContext()); // Click the item. onView(withText("World")) .perform(click()); // Verify that we have really clicked on the icon by checking // the TextView content. onView(withId(R.id.text_action_bar_result)) .check(matches(withText("World"))); }

在配備硬體溢位選單按鈕的裝置上,這會顯示如下:

關聯動作列也同樣容易:
Kotlin
fun testActionModeOverflow() { // Show the contextual action bar. onView(withId(R.id.show_contextual_action_bar)) .perform(click()) // Open the overflow menu from contextual action mode. openContextualActionModeOverflowMenu() // Click on the item. onView(withText("Key")) .perform(click()) // Verify that we have really clicked on the icon by // checking the TextView content. onView(withId(R.id.text_action_bar_result)) .check(matches(withText("Key"))) } }
Java
public void testActionModeOverflow() { // Show the contextual action bar. onView(withId(R.id.show_contextual_action_bar)) .perform(click()); // Open the overflow menu from contextual action mode. openContextualActionModeOverflowMenu(); // Click on the item. onView(withText("Key")) .perform(click()); // Verify that we have really clicked on the icon by // checking the TextView content. onView(withId(R.id.text_action_bar_result)) .check(matches(withText("Key"))); } }

如要查看這些範例的完整程式碼,請前往 GitHub 上的 ActionBarTest.java 範例。
宣告未顯示檢視畫面
執行一系列動作後,您一定會想斷言受測 UI 的狀態。有時這可能是負面情況,例如某事未發生。請注意,您可以使用 ViewAssertions.matches() 將任何 Hamcrest 檢視比對器轉換為 ViewAssertion。
在以下範例中,我們使用標準 not() 比對器,將 isDisplayed() 比對器反轉:
Kotlin
import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import org.hamcrest.Matchers.not onView(withId(R.id.bottom_left)) .check(matches(not(isDisplayed())))
Java
import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static org.hamcrest.Matchers.not; onView(withId(R.id.bottom_left)) .check(matches(not(isDisplayed())));
如果檢視畫面仍是階層的一部分,上述方法就適用。如果不是,您會收到 NoMatchingViewException,且需要使用 ViewAssertions.doesNotExist()。
宣告檢視畫面不存在
如果檢視畫面已從檢視區塊階層中消失 (可能發生在某個動作導致轉換至其他活動時),請使用 ViewAssertions.doesNotExist():
Kotlin
import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.doesNotExist import androidx.test.espresso.matcher.ViewMatchers.withId onView(withId(R.id.bottom_left)) .check(doesNotExist())
Java
import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.assertion.ViewAssertions.doesNotExist; import static androidx.test.espresso.matcher.ViewMatchers.withId; onView(withId(R.id.bottom_left)) .check(doesNotExist());
宣告資料項目不在轉接器中
如要證明特定資料項目不在 AdapterView 中,您必須採取稍微不同的做法。我們必須找出感興趣的 AdapterView,並查詢其中保存的資料。我們不需要使用 onData()。而是使用 onView() 尋找 AdapterView,然後使用另一個比對器處理檢視畫面中的資料。
首先是比對器:
Kotlin
private fun withAdaptedData(dataMatcher: Matcher<Any>): Matcher<View> { return object : TypeSafeMatcher<View>() { override fun describeTo(description: Description) { description.appendText("with class name: ") dataMatcher.describeTo(description) } public override fun matchesSafely(view: View) : Boolean { if (view !is AdapterView<*>) { return false } val adapter = view.adapter for (i in 0 until adapter.count) { if (dataMatcher.matches(adapter.getItem(i))) { return true } } return false } } }
Java
private static Matcher<View> withAdaptedData(final Matcher<Object> dataMatcher) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("with class name: "); dataMatcher.describeTo(description); } @Override public boolean matchesSafely(View view) { if (!(view instanceof AdapterView)) { return false; } @SuppressWarnings("rawtypes") Adapter adapter = ((AdapterView) view).getAdapter(); for (int i = 0; i < adapter.getCount(); i++) { if (dataMatcher.matches(adapter.getItem(i))) { return true; } } return false; } }; }
接著,我們只需要 onView() 即可找出 AdapterView:
Kotlin
fun testDataItemNotInAdapter() { onView(withId(R.id.list)) .check(matches(not(withAdaptedData(withItemContent("item: 168"))))) } }
Java
@SuppressWarnings("unchecked") public void testDataItemNotInAdapter() { onView(withId(R.id.list)) .check(matches(not(withAdaptedData(withItemContent("item: 168"))))); } }
如果 ID 清單的轉接器檢視畫面中存在等於「item: 168」的項目,則斷言會失敗。
如需完整範例,請參閱 GitHub 上 AdapterViewTest.java 類別中的 testDataItemNotInAdapter() 方法。
使用自訂失敗處理常式
將 Espresso 中的預設 FailureHandler 替換為自訂項目,即可執行額外或不同的錯誤處理,例如擷取螢幕截圖或傳遞額外的偵錯資訊。
CustomFailureHandlerTest 範例示範如何實作自訂失敗處理常式:
Kotlin
private class CustomFailureHandler(targetContext: Context) : FailureHandler { private val delegate: FailureHandler init { delegate = DefaultFailureHandler(targetContext) } override fun handle(error: Throwable, viewMatcher: Matcher<View>) { try { delegate.handle(error, viewMatcher) } catch (e: NoMatchingViewException) { throw MySpecialException(e) } } }
Java
private static class CustomFailureHandler implements FailureHandler { private final FailureHandler delegate; public CustomFailureHandler(Context targetContext) { delegate = new DefaultFailureHandler(targetContext); } @Override public void handle(Throwable error, Matcher<View> viewMatcher) { try { delegate.handle(error, viewMatcher); } catch (NoMatchingViewException e) { throw new MySpecialException(e); } } }
這個失敗處理常式會擲回 MySpecialException,而不是 NoMatchingViewException,並將所有其他失敗委派給 DefaultFailureHandler。CustomFailureHandler 可在測試的 setUp() 方法中向 Espresso 註冊:
Kotlin
@Throws(Exception::class) override fun setUp() { super.setUp() getActivity() setFailureHandler(CustomFailureHandler( ApplicationProvider.getApplicationContext<Context>())) }
Java
@Override public void setUp() throws Exception { super.setUp(); getActivity(); setFailureHandler(new CustomFailureHandler( ApplicationProvider.getApplicationContext())); }
詳情請參閱 FailureHandler 介面和 Espresso.setFailureHandler()。
指定非預設視窗
Android 支援多視窗模式。一般來說,使用者和應用程式開發人員不會察覺到這項作業,但在某些情況下,系統會顯示多個視窗,例如在搜尋小工具中,自動完成視窗會繪製在主應用程式視窗上方。為簡化作業,Espresso 預設會使用經驗法則,猜測您要與哪個 Window 互動。這種經驗法則幾乎總是有效,但在少數情況下,您需要指定互動應指定的視窗。如要這麼做,請提供自己的根視窗比對器或 Root 比對器:
Kotlin
onView(withText("South China Sea")) .inRoot(withDecorView(not(`is`(getActivity().getWindow().getDecorView())))) .perform(click())
Java
onView(withText("South China Sea")) .inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView())))) .perform(click());
與 androidx.test.espresso.matcher.ViewMatchers 類似,Espresso 在 androidx.test.espresso.matcher.RootMatchers 中提供內建根比對器,例如 withDecorView()、isDialog() 和 isPlatformPopup()。如要快速查看內建比對器的視覺摘要,請參閱 Espresso 快速入門指南,或實作自己的 Matcher<Root> 物件。
請參閱 GitHub 上的 MultipleWindowTest 範例。
比對清單檢視中的頁首或頁尾
您可以使用 addHeaderView() 和 addFooterView() 方法,將頁首和頁尾新增至 ListViews。為確保 Espresso.onData() 知道要比對的資料物件,請務必將預設資料物件值做為第二個參數傳遞至 addHeaderView() 和 addFooterView()。例如:
Kotlin
const val FOOTER = "FOOTER" ... val footerView = layoutInflater.inflate(R.layout.list_item, listView, false) footerView.findViewById<TextView>(R.id.item_content).text = "count:" footerView.findViewById<TextView>(R.id.item_size).text = data.size.toString listView.addFooterView(footerView, FOOTER, true)
Java
public static final String FOOTER = "FOOTER"; ... View footerView = layoutInflater.inflate(R.layout.list_item, listView, false); footerView.findViewById<TextView>(R.id.item_content).setText("count:"); footerView.findViewById<TextView>(R.id.item_size).setText(String.valueOf(data.size())); listView.addFooterView(footerView, FOOTER, true);
接著,您可以為頁尾編寫比對器:
Kotlin
import org.hamcrest.Matchers.allOf import org.hamcrest.Matchers.instanceOf import org.hamcrest.Matchers.`is` fun isFooter(): Matcher<Any> { return allOf(`is`(instanceOf(String::class.java)), `is`(LongListActivity.FOOTER)) }
Java
import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; @SuppressWarnings("unchecked") public static Matcher<Object> isFooter() { return allOf(is(instanceOf(String.class)), is(LongListActivity.FOOTER)); }
在測試中載入檢視畫面非常簡單:
Kotlin
import androidx.test.espresso.Espresso.onData import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.sample.LongListMatchers.isFooter fun testClickFooter() { onData(isFooter()) .perform(click()) // ... }
Java
import static androidx.test.espresso.Espresso.onData; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.sample.LongListMatchers.isFooter; public void testClickFooter() { onData(isFooter()) .perform(click()); // ... }
請查看 GitHub 上 AdapterViewTest.java 的 testClickFooter() 方法中的完整程式碼範例。