さまざまな画面サイズをテストするためのライブラリとツール

Android には、アプリのテストの作成に役立つさまざまなツールと API が用意されています。 各種画面やウィンドウ サイズに対応できます。

DeviceConfigurationOverride

DeviceConfigurationOverride コンポーザブルを使用すると、 Compose で複数の画面サイズとウィンドウ サイズをテストするための構成属性 できます。ForcedSize オーバーライドは、使用可能なスペースのあらゆるレイアウトに適合します。 任意の実行環境で あらゆる画面サイズでの UI テスト。たとえば、小型のスマートフォン フォーム ファクタを使用して、 すべての UI テストを実行できます。これには、大型スマートフォン、折りたたみ式デバイス、Android デバイスの UI テストが含まれます。 。

   DeviceConfigurationOverride(
        DeviceConfigurationOverride.ForcedSize(DpSize(1280.dp, 800.dp))
    ) {
        MyScreen() // Will be rendered in the space for 1280dp by 800dp without clipping.
    }
<ph type="x-smartling-placeholder">
</ph>
図 1.「*Now in Android*」のように、DeviceConfigurationOverride を使用してタブレット レイアウトを小型のフォーム ファクタ デバイス内に収めます。

さらに、このコンポーザブルを使用して、フォントのスケール、テーマ、その他のカスタム さまざまなウィンドウ サイズでテストできます。

Robolectric

Robolectric を使用して、JVM で Compose またはビューベースの UI テストを実行します。 ローカル - デバイスまたはエミュレータは必要ありません。構成できます。 Robolectric を使用して、特定の画面サイズや便利なプロパティを使用できます。

以下の Now in Androidでは、Robolectric が構成されています。 次のように、解像度 480 dpi で 1000x1000 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 プラグイン を使用すると、エミュレータと実際のデバイスの インストルメンテーション テストの実行。以下を搭載したデバイスの仕様を作成します。 さまざまな画面サイズでテスト戦略を実装できます。 特定の画面サイズで実行できます継続的インテグレーションで 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 は、エミュレータでのテスト実行もサポートしています。 これらのサービスにより、インストルメンテーション テストの信頼性と速度が向上します。 デバイスやエミュレータを事前にプロビジョニングできます。

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()
}

ウィンドウ テスト ライブラリ

ウィンドウ テスト ライブラリには、Terraform を使用するテストの記述に役立つユーティリティが ウィンドウ管理に関連する機能の有効化や検証を行います。たとえば、 組み込みや折りたたみ式機能などです。このアーティファクトは、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() 関数を使用します。 次の例では、FoldingFeature が次のようにシミュレートされます。 HALF_OPENED 画面中央にある垂直ヒンジを使用して 想定どおりです。

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()
    }
}

View

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 プロジェクトをご覧ください。

参考情報

ドキュメント

サンプル

Codelab