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 が解像度 480 dpi で画面サイズ 1,000x1,000 dp をエミュレートするように構成されています。
@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()
は、新しい構成でシステム リソースとアプリケーション リソースを更新しますが、アクティブなアクティビティやその他のコンポーネントに対するアクションをトリガーしません。
詳しくは、Robolectric デバイス構成のドキュメントをご覧ください。
Gradle で管理されているデバイス
Gradle で管理されているデバイス(GMD)Android Gradle プラグインを使用すると、インストルメンテーション テストを実行するエミュレータと実際のデバイスの仕様を定義できます。さまざまな画面サイズのデバイスの仕様を作成して、特定のテストを特定の画面サイズで実行する必要があるテスト戦略を実装します。継続的インテグレーション(CI)で GMD を使用すると、必要に応じて適切なテストが実行されるようにして、エミュレータをプロビジョニングして起動し、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 は、エミュレータでのテスト実行もサポートしています。これらのサービスはデバイスとエミュレータを事前にプロビジョニングできるため、インストルメンテーション テストの信頼性と速度が向上します。
GMD で FTL を使用する方法については、Gradle で管理されているデバイスを使用したテストのスケーリングをご覧ください。
テストランナーを使用したテスト フィルタリング
同じものを 2 回検証することが最適なテスト戦略ではなくなるため、ほとんどの 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 デバイス(次のセクションを参照)では、デバイス プロパティを使用してテストをフィルタリングすることもできます。
Espresso デバイス
Espresso デバイスを使用すると、Espresso、Compose、UI Automator テストなど、あらゆる種類のインストルメンテーション テストを使用して、テストでエミュレータに対してアクションを実行できます。これらのアクションには、画面サイズの設定や、折りたたみ式デバイスの状態や形状の切り替えなどがあります。たとえば、折りたたみ式エミュレータを制御して、テーブルトップ モードに設定できます。Espresso デバイスには、特定の機能を要求する 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 デバイスはまだアルファ版であり、次の要件があります。
- Android Gradle プラグイン 8.3 以降
- Android Emulator 33.1.10 以降
- API レベル 24 以降を搭載している Android 仮想デバイス
テストをフィルタリングする
Espresso デバイスは、接続されたデバイスのプロパティを読み取ることで、アノテーションを使用してテストをフィルタリングできます。アノテーション付きの要件が満たされていない場合、テストはスキップされます。
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
クラスは、アクティビティを再作成せずにコンポーズ可能なコンポーネントの状態復元をテストするために使用されます。アクティビティの再作成は複数の同期メカニズムを含む複雑なプロセスであるため、これにより、テストの速度と信頼性が向上します。
@Test
fun compactDevice_selectedEmailEmailRetained_afterConfigChange() {
val stateRestorationTester = StateRestorationTester(composeTestRule)
// Set content through the StateRestorationTester object.
stateRestorationTester.setContent {
MyApp()
}
// Simulate a config change.
stateRestorationTester.emulateSavedInstanceStateRestore()
}
ウィンドウ テスト ライブラリ
ウィンドウ テスト ライブラリには、アクティビティの埋め込みや折りたたみ式機能など、ウィンドウ管理に関連する機能に依存または検証するテストの作成に役立つユーティリティが含まれています。このアーティファクトは、Google の Maven リポジトリから入手できます。
たとえば、FoldingFeature()
関数を使用して、Compose プレビューで使用できるカスタム FoldingFeature
を生成できます。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
をシミュレートし、レイアウトが想定どおりかどうかを確認します。
文章
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()
}
}
視聴回数
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 デバイスのサンプル
- Now In Android
- スクリーンショット テストを使用してさまざまな画面サイズを検証する
Codelab