模擬 Surface Duo 上的撥動手勢

UiAutomator 是一種測試架構,可提供跨應用程式測試功能和裝置感應器的存取權。 swipe使用UiDevice類別和裝置維度中的方法,您可以在測試期間模擬 Surface Duo 上的不同手勢。

Test Kit 提供公用程式函式,可在不同的座標之間執行撥動,以模擬跨越應用程式、取消流覽應用程式、在螢幕之間切換應用程式,以及關閉應用程式。

安裝程式

  1. androidTest 目錄中建立新的測試類別檔案。 您稍後會在此新增測試規則和測試的程式碼片段。

  2. 請確定您在最上層build.gradle檔案中有存放 mavenCentral() 庫:

    allprojects {
        repositories {
            google()
            mavenCentral()
         }
    }
    
  3. 將下列相依性新增至模組層級 build.gradle 檔案, (目前的版本可能與此處所示) 不同:

    androidTestImplementation "com.microsoft.device.dualscreen.testing:testing-kotlin:1.0.0-alpha4"
    androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
    androidTestImplementation "androidx.test.espresso:espresso-core:3.4.0"
    androidTestImplementation "androidx.test:runner:1.4.0"
    androidTestImplementation "androidx.test:rules:1.4.0"
    
  4. compileSdkVersion確定 已設定為 API 33, targetSdkVersion 並將 設定為模組層級build.gradle檔案中的 API 32 或更新版本:

    android { 
        compileSdkVersion 33
    
        defaultConfig { 
            targetSdkVersion 32 
        } 
        ... 
    }
    
  5. TestRule 測試類別內建立 UiDevice 和 實例。

    @get:Rule
    val activityRule = ActivityScenarioRule(MainActivity::class.java)
    private val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
    
  6. 如果您使用 一元測試檢視,請務必停用裝置上的 動畫

如何撰寫測試

在 Test Kit 程式庫中,我們提供在 Surface Duo 上執行 顯示作業 的選項。 所有這些方法都會使用 撥 方法, UiDevice 以模擬不同座標之間的撥動。 若要讓您的測試盡可能可靠,建議您在撥動之間執行判斷提示和檢查,並將每個測試中執行的撥動數目降到最低。

若要撰寫使用撥動手勢的測試,請遵循下列步驟:

  1. 執行撥動手勢
  2. 判斷提示 UI 已如預期般變更

下列範例測試示範應用程式在跨越時顯示兩個窗格的簡單 UI 測試。

@Test
fun testSpan() {
    onView(withText("pane 1")).check(matches(isDisplayed()))

    // 1. Perform swipe gesture
    device.spanFromStart()

    // 2. Assert that UI has changed as expected
    onView(withText("pane 1")).check(matches(isDisplayed()))
    onView(withText("pane 2")).check(matches(isDisplayed()))
}

下列動畫顯示Surface Duo 模擬器上執行時的外觀 testSpan

在 Surface Duo 模擬器上執行的 testSpan 測試

範例

若要查看如何在 Surface Duo 測試中使用模擬撥動手勢的更多範例,請參閱下列資源:

資源

若要深入瞭解已檢測的測試與 UiAutomator,請參閱下列資源: