模拟 Surface Duo 上的轻扫手势

UiAutomator 是一种测试框架,提供跨应用测试功能以及对设备传感器的访问。 使用 UiDevice 类中的 swipe 方法和设备尺寸,可以在测试中模拟 Surface Duo 上的不同手势。

此测试工具包提供了在不同坐标之间执行轻扫以模拟跨越应用、取消跨越应用、在屏幕之间切换应用和关闭应用的实用工具功能。

设置

  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确保在模块级别 build.gradle 文件中将 设置为 API 33,并将 targetSdkVersion 设置为 API 32 或更高版本:

    android { 
        compileSdkVersion 33
    
        defaultConfig { 
            targetSdkVersion 32 
        } 
        ... 
    }
    
  5. 在测试类中创建 TestRuleUiDevice 实例。

    @get:Rule
    val activityRule = ActivityScenarioRule(MainActivity::class.java)
    private val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
    
  6. 如果使用 Espresso 测试视图,请确保在设备上禁用动画

如何编写测试

在测试工具包库中,我们提供了用于在 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()))
}

以下动画演示了 testSpanSurface Duo 模拟器上运行时的外观:

在 Surface Duo 模拟器上运行的 testSpan 测试

示例

若要查看有关如何在 Surface Duo 测试中使用模拟轻扫手势的更多示例,请查看以下资源:

资源

若要了解有关已检测测试和 UiAutomator 的详细信息,请查看以下资源: