- Espresso Testing 框架教程
- Espresso Testing - 主頁
- 介紹
- 設定說明
- 在 Android Studio 中執行測試
- JUnit 概述
- 架構
- 檢視匹配器
- 自定義檢視匹配器
- 檢視斷言
- 檢視操作
- 測試 AdapterView
- 測試 WebView
- 測試非同步操作
- 測試意向
- 測試多個應用程式的 UI
- 測試記錄器
- 測試 UI 效能
- 測試可訪問性
- Espresso Testing 資源
- Espresso Testing - 快速指南
- Espresso Testing - 有用資源
- Espresso Testing - 討論
Espresso Testing 框架 - 測試記錄器
編寫測試用例是一項繁瑣的工作。即使 Espresso 提供了非常簡單靈活的 API,但編寫測試用例可能是一項懶惰且耗時的任務。為了克服這個問題,Android Studio 提供了一項用於記錄和生成 Espresso 測試用例的功能。Record Espresso Test 在Run 選單下可用。
讓我們按照以下步驟在HelloWorldApp 中記錄一個簡單的測試用例。
開啟 Android Studio,然後開啟HelloWorldApp 應用程式。
單擊Run → Record Espresso 測試並選擇MainActivity。
Recorder 螢幕截圖如下所示,
單擊Add Assertion。它將開啟應用程式螢幕,如下所示,
單擊Hello World!。選擇文字檢視的Recorder 螢幕如下所示,
再次單擊Save Assertion,這將儲存斷言並顯示如下所示,
單擊OK。它將開啟一個新視窗並詢問測試用例的名稱。預設名稱為MainActivityTest
如果需要,更改測試用例名稱。
再次單擊OK。這將生成一個檔案MainActivityTest,其中包含我們記錄的測試用例。完整的編碼如下所示,
package com.tutorialspoint.espressosamples.helloworldapp;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.espresso.ViewInteraction;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
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 androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void mainActivityTest() {
ViewInteraction textView = onView(
allOf(withId(R.id.textView_hello), withText("Hello World!"),
childAtPosition(childAtPosition(withId(android.R.id.content),
0),0),isDisplayed()));
textView.check(matches(withText("Hello World!")));
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup &&
parentMatcher.matches(parent)&& view.equals(((ViewGroup)
parent).getChildAt(position));
}
};
}
}
最後,使用上下文選單執行測試並檢查測試用例是否執行。
廣告