Android 提供了多种工具和 API,可以帮助您针对不同的屏幕和窗口尺寸创建测试。
DeviceConfigurationOverride
DeviceConfigurationOverride 可组合项允许您覆盖配置属性,以便在 Compose 布局中测试多种屏幕和窗口尺寸。ForcedSize 覆盖会将任何布局适配到可用空间中,这让您可以在任何屏幕尺寸上运行任何界面 (UI) 测试。例如,您可以使用小型手机外形规格来运行所有 UI 测试,包括针对大屏手机、可折叠设备和平板电脑的 UI 测试。
DeviceConfigurationOverride(
DeviceConfigurationOverride.ForcedSize(DpSize(1280.dp, 800.dp))
) {
MyScreen() // Will be rendered in the space for 1280dp by 800dp without clipping.
}
此外,您还可以使用此可组合项设置字体缩放、主题以及您可能希望在不同窗口尺寸下测试的其他属性。
Robolectric
使用 Robolectric 在 JVM 上本地运行 Compose 或基于视图的 UI 测试——无需设备或模拟器。您可以配置 Robolectric 以使用特定的屏幕尺寸,以及其他有用的属性。
在来自 Now in Android 的以下示例中,Robolectric 被配置为模拟 1000x1000 dp、分辨率为 480 dpi 的屏幕尺寸。
@RunWith(RobolectricTestRunner::class)
// Configure Robolectric to use a very large screen size that can fit all of the test sizes.
// This allows enough room to render the content under test without clipping or scaling.
@Config(qualifiers = "w1000dp-h1000dp-480dpi")
class NiaAppScreenSizesScreenshotTests { ... }
您也可以像在 Now in Android 示例的这段代码片段中所做的那样,从测试主体中设置限定符。
val (width, height, dpi) = ...
// Set qualifiers from specs.
RuntimeEnvironment.setQualifiers("w${width}dp-h${height}dp-${dpi}dpi")
请注意,RuntimeEnvironment.setQualifiers() 会使用新配置更新系统和应用程序资源,但不会对处于活动状态的 Activity 或其他组件触发任何操作。
您可以在 Robolectric 设备配置文档中阅读更多内容。
Gradle 管理的设备
Gradle 管理的设备 (GMD) Android Gradle 插件允许您定义运行插桩测试所需的模拟器和真实设备的规格。为不同屏幕尺寸的设备创建规格,从而实现一种测试策略,即确保特定测试必须在特定屏幕尺寸上运行。通过将 GMD 与持续集成 (CI) 结合使用,您可以确保在需要时运行相应的测试,并自动配置和启动模拟器,从而简化 CI 设置。
android {
testOptions {
managedDevices {
devices {
// Run with ./gradlew nexusOneApi30DebugAndroidTest.
nexusOneApi30(com.android.build.api.dsl.ManagedVirtualDevice) {
device = "Nexus One"
apiLevel = 30
// Use the AOSP ATD image for better emulator performance
systemImageSource = "aosp-atd"
}
// Run with ./gradlew foldApi34DebugAndroidTest.
foldApi34(com.android.build.api.dsl.ManagedVirtualDevice) {
device = "Pixel Fold"
apiLevel = 34
systemImageSource = "aosp-atd"
}
}
}
}
}
您可以在 testing-samples 项目中找到多个 GMD 示例。
Firebase Test Lab
使用 Firebase Test Lab (FTL) 或类似的设备场服务,可以在您可能无法访问的特定真实设备(例如各种尺寸的可折叠设备或平板电脑)上运行测试。Firebase Test Lab 是一项付费服务,但也提供免费层级。FTL 还支持在模拟器上运行测试。这些服务提高了插桩测试的可靠性和速度,因为它们可以提前配置设备和模拟器。
有关将 FTL 与 GMD 结合使用的信息,请参阅使用 Gradle 管理的设备扩展测试规模。
使用测试运行程序进行测试过滤
最优的测试策略不应重复验证相同的内容,因此大多数 UI 测试不需要在多个设备上运行。通常,您的做法是过滤 UI 测试,即在手机外形规格上运行所有或大部分测试,仅在具有不同屏幕尺寸的设备上运行一部分测试。
您可以为特定测试添加注解,使其仅在特定设备上运行,然后在运行测试的命令中向 AndroidJUnitRunner 传递参数。
例如,您可以创建不同的注解
annotation class TestExpandedWidth
annotation class TestCompactWidth
并在不同的测试中使用它们
class MyTestClass {
@Test
@TestExpandedWidth
fun myExample_worksOnTablet() {
...
}
@Test
@TestCompactWidth
fun myExample_worksOnPortraitPhone() {
...
}
}
随后,您可以在运行测试时使用 android.testInstrumentationRunnerArguments.annotation 属性来过滤特定的测试。例如,如果您使用的是 Gradle 管理的设备
$ ./gradlew pixelTabletApi30DebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.annotation='com.sample.TestExpandedWidth'
如果您不使用 GMD 且在 CI 上管理模拟器,请先确保正确的模拟器或设备已准备就绪并已连接,然后将参数传递给运行插桩测试的 Gradle 命令之一
$ ./gradlew connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.annotation='com.sample.TestExpandedWidth'
请注意,Espresso Device(见下一节)也可以通过使用设备属性来过滤测试。
Espresso Device
使用 Espresso Device,可以在任何类型的插桩测试(包括 Espresso、Compose 或 UI Automator 测试)中使用它对测试中的模拟器执行操作。这些操作可能包括设置屏幕尺寸或切换可折叠设备的状态或姿势。例如,您可以控制可折叠模拟器并将其设置为桌面模式。Espresso Device 还包含用于要求特定功能的 JUnit 规则和注解。
@RunWith(AndroidJUnit4::class)
class OnDeviceTest {
@get:Rule(order=1) val activityScenarioRule = activityScenarioRule<MainActivity>()
@get:Rule(order=2) val screenOrientationRule: ScreenOrientationRule =
ScreenOrientationRule(ScreenOrientation.PORTRAIT)
@Test
fun tabletopMode_playerIsDisplayed() {
// Set the device to tabletop mode.
onDevice().setTabletopMode()
onView(withId(R.id.player)).check(matches(isDisplayed()))
}
}
请注意,Espresso Device 仍处于 Alpha 阶段,并具有以下要求
- Android Gradle 插件 8.3 或更高版本
- Android 模拟器 33.1.10 或更高版本
- 运行 API 级别 24 或更高级别的 Android 虚拟设备
过滤测试
Espresso Device 可以读取连接设备的属性,使您能够使用注解来过滤测试。如果不满足注解要求的条件,测试将被跳过。
RequiresDeviceMode 注解
RequiresDeviceMode 注解可以多次使用,以指示测试仅在设备支持所有 DeviceMode 值时才会运行。
class OnDeviceTest {
...
@Test
@RequiresDeviceMode(TABLETOP)
@RequiresDeviceMode(BOOK)
fun tabletopMode_playerIdDisplayed() {
// Set the device to tabletop mode.
onDevice().setTabletopMode()
onView(withId(R.id.player)).check(matches(isDisplayed()))
}
}
RequiresDisplay 注解
RequiresDisplay 注解允许您使用尺寸类别指定设备屏幕的宽度和高度,这些类别定义了遵循官方窗口尺寸类别的维度区间。
class OnDeviceTest {
...
@Test
@RequiresDisplay(EXPANDED, COMPACT)
fun myScreen_expandedWidthCompactHeight() {
...
}
}
调整显示大小
使用 setDisplaySize() 方法在运行时调整屏幕尺寸。请结合 DisplaySizeRule 类使用此方法,该类可确保测试期间所做的任何更改在下一次测试前都会还原。
@RunWith(AndroidJUnit4::class)
class ResizeDisplayTest {
@get:Rule(order = 1) val activityScenarioRule = activityScenarioRule<MainActivity>()
// Test rule for restoring device to its starting display size when a test case finishes.
@get:Rule(order = 2) val displaySizeRule: DisplaySizeRule = DisplaySizeRule()
@Test
fun resizeWindow_compact() {
onDevice().setDisplaySize(
widthSizeClass = WidthSizeClass.COMPACT,
heightSizeClass = HeightSizeClass.COMPACT
)
// Verify visual attributes or state restoration.
}
}
当您使用 setDisplaySize() 调整显示大小时,不会影响设备的像素密度,因此如果某个维度不适合目标设备,测试将抛出 UnsupportedDeviceOperationException 而失败。为防止测试在这种情况下运行,请使用 RequiresDisplay 注解将其过滤掉。
@RunWith(AndroidJUnit4::class)
class ResizeDisplayTest {
@get:Rule(order = 1) var activityScenarioRule = activityScenarioRule<MainActivity>()
// Test rule for restoring device to its starting display size when a test case finishes.
@get:Rule(order = 2) var displaySizeRule: DisplaySizeRule = DisplaySizeRule()
/**
* Setting the display size to EXPANDED would fail in small devices, so the [RequiresDisplay]
* annotation prevents this test from being run on devices outside the EXPANDED buckets.
*/
@RequiresDisplay(
widthSizeClass = WidthSizeClassEnum.EXPANDED,
heightSizeClass = HeightSizeClassEnum.EXPANDED
)
@Test
fun resizeWindow_expanded() {
onDevice().setDisplaySize(
widthSizeClass = WidthSizeClass.EXPANDED,
heightSizeClass = HeightSizeClass.EXPANDED
)
// Verify visual attributes or state restoration.
}
}
StateRestorationTester
StateRestorationTester 类用于测试可组合组件的状态恢复,而无需重新创建 Activity。这使得测试更快、更可靠,因为 Activity 重建是一个涉及多种同步机制的复杂过程。
@Test
fun compactDevice_selectedEmailEmailRetained_afterConfigChange() {
val stateRestorationTester = StateRestorationTester(composeTestRule)
// Set content through the StateRestorationTester object.
stateRestorationTester.setContent {
MyApp()
}
// Simulate a config change.
stateRestorationTester.emulateSavedInstanceStateRestore()
}
Window Testing 库
Window Testing 库包含了一些实用程序,可帮助您编写依赖或验证窗口管理相关功能(如Activity 嵌入或可折叠功能)的测试。该工件可通过 Google Maven 仓库获取。
例如,您可以使用 FoldingFeature() 函数生成一个自定义的 FoldingFeature,并将其用于 Compose 预览中。在 Java 中,请使用 createFoldingFeature() 函数。
在 Compose 预览中,您可以按以下方式实现 FoldingFeature
@Preview(showBackground = true, widthDp = 480, heightDp = 480)
@Composable private fun FoldablePreview() =
MyApplicationTheme {
ExampleScreen(
displayFeatures = listOf(FoldingFeature(Rect(0, 240, 480, 240)))
)
}
此外,您还可以使用 TestWindowLayoutInfo() 函数在 UI 测试中模拟显示功能。以下示例模拟了一个在屏幕中心带有垂直铰链且处于 HALF_OPENED 状态的 FoldingFeature,然后检查布局是否符合预期。
Compose
import androidx.window.layout.FoldingFeature.Orientation.Companion.VERTICAL
import androidx.window.layout.FoldingFeature.State.Companion.HALF_OPENED
import androidx.window.testing.layout.FoldingFeature
import androidx.window.testing.layout.TestWindowLayoutInfo
import androidx.window.testing.layout.WindowLayoutInfoPublisherRule
@RunWith(AndroidJUnit4::class)
class MediaControlsFoldingFeatureTest {
@get:Rule(order=1)
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@get:Rule(order=2)
val windowLayoutInfoPublisherRule = WindowLayoutInfoPublisherRule()
@Test
fun foldedWithHinge_foldableUiDisplayed() {
composeTestRule.setContent {
MediaPlayerScreen()
}
val hinge = FoldingFeature(
activity = composeTestRule.activity,
state = HALF_OPENED,
orientation = VERTICAL,
size = 2
)
val expected = TestWindowLayoutInfo(listOf(hinge))
windowLayoutInfoPublisherRule.overrideWindowLayoutInfo(expected)
composeTestRule.waitForIdle()
// Verify that the folding feature is detected and media controls shown.
composeTestRule.onNodeWithTag("MEDIA_CONTROLS").assertExists()
}
}
视图 (Views)
import androidx.window.layout.FoldingFeature.Orientation
import androidx.window.layout.FoldingFeature.State
import androidx.window.testing.layout.FoldingFeature
import androidx.window.testing.layout.TestWindowLayoutInfo
import androidx.window.testing.layout.WindowLayoutInfoPublisherRule
@RunWith(AndroidJUnit4::class)
class MediaControlsFoldingFeatureTest {
@get:Rule(order=1)
val activityRule = ActivityScenarioRule(MediaPlayerActivity::class.java)
@get:Rule(order=2)
val windowLayoutInfoPublisherRule = WindowLayoutInfoPublisherRule()
@Test
fun foldedWithHinge_foldableUiDisplayed() {
activityRule.scenario.onActivity { activity ->
val feature = FoldingFeature(
activity = activity,
state = State.HALF_OPENED,
orientation = Orientation.VERTICAL)
val expected = TestWindowLayoutInfo(listOf(feature))
windowLayoutInfoPublisherRule.overrideWindowLayoutInfo(expected)
}
// Verify that the folding feature is detected and media controls shown.
onView(withId(R.id.media_controls)).check(matches(isDisplayed()))
}
}
您可以在 WindowManager 项目中找到更多示例。
其他资源
文档
示例
- WindowManager 示例
- Espresso Device 示例
- Now In Android
- 使用屏幕截图测试来验证不同的屏幕尺寸
Codelabs