您可以使用 Glance 單元測試 API 測試 Glance 程式碼,不必擴充檢視區塊或使用 UI 自動化工具。舉例來說,您可以使用 hasContentDescriptionEqualTo 或 isChecked 等比對器,透過單元測試 API 驗證條件,例如元素是否位於清單中,或方塊是否已勾選。
這個 API 輕巧且設定較少,因此您可以在開發小工具的個別部分時執行測試導向開發,並整理這些部分以提高程式碼重複使用率。
設定
下列範例顯示使用單元測試程式庫所需的依附元件:
// Other Glance and Compose runtime dependencies....testImplementation'androidx.glance:glance-testing:1.1.1'testImplementation'androidx.glance:glance-appwidget-testing:1.1.1'testImplementation'org.robolectric:robolectric:4.11.1'...// You may include additional dependencies, such as Robolectric, if your test// needs to set a LocalContext.
classMyGlanceComposableTest{@TestfunmyNewsItemComposable_largeSize_hasAuthorAsSubtitle()=runGlanceAppWidgetUnitTest{// Prepare inputs and statesetAppWidgetSize(100.dp,100.dp)// Set the composable under testprovideComposable{MyNewsItemComposable(TEST_NEWS_ITEM)}// Perform assertionsonNode(hasTestTag("subTitle")).assertHasText(TEST_NEWS_ITEM.authorName)}}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-21 (世界標準時間)。"],[],[],null,["The Glance unit test API let you test your Glance code without inflating views\nor needing a UI automator. For example, the unit test API lets you verify\nconditions, such as whether elements are in a list or whether boxes have been\nchecked, using matchers such as `hasContentDescriptionEqualTo` or `isChecked`.\n\nThis API is lightweight and requires less setup, so you can perform test driven\ndevelopment as you develop individual pieces of your widget and organize them to\nimprove code reuse.\n| **Note:** The test doesn't render the composables under test, so it doesn't let you perform clicks. Instead, it uses matchers, which let you perform assertions on actions in clickables such as starting a service or activity.\n\nSetup\n\nThe dependencies required to use the unit test library are shown in the\nfollowing examples: \n\n // Other Glance and Compose runtime dependencies.\n ...\n testImplementation 'androidx.glance:glance-testing:1.1.1'\n testImplementation 'androidx.glance:glance-appwidget-testing:1.1.1'\n testImplementation 'org.robolectric:robolectric:4.11.1'\n ...\n // You may include additional dependencies, such as Robolectric, if your test\n // needs to set a LocalContext.\n\nTest structure\n\nOrganize composable functions outside of the `GlanceAppWidget` class to enable\ncode reuse and unit testing. Reduce the complexity of your units under test as\nmuch as possible. \n\n class MyGlanceComposableTest {\n @Test\n fun myNewsItemComposable_largeSize_hasAuthorAsSubtitle() = runGlanceAppWidgetUnitTest {\n // Prepare inputs and state\n setAppWidgetSize(100.dp, 100.dp)\n\n // Set the composable under test\n provideComposable {\n MyNewsItemComposable(TEST_NEWS_ITEM)\n }\n\n // Perform assertions\n onNode(hasTestTag(\"subTitle\"))\n .assertHasText(TEST_NEWS_ITEM.authorName)\n }\n }\n\nSet context and size for the test\n\nIf your composable function reads context using the `LocalContext.current()`\nmethod, you must set a context using `setContext()`. Otherwise, this step is\noptional.\n\nYou can use any JVM-based Android unit testing framework, such as Roboletric, to\nprovide the context.\n\nIf your composable function accesses `LocalSize`, set the intended size\nfor the test before providing a composable in the test. The default size is\n349.dp x 455.dp, which is equivalent to a 5x4 widget shown on a Pixel 4 device\nin portrait mode.\n\n- If your AppWidget uses `sizeMode == Single`, you can set this to the `minWidth` and `minHeight` in your widget's `info.xml` file.\n- If your AppWidget uses `sizeMode == Exact`, you can identify the sizes to test in a similar way to how you [determine a size for your widget](/develop/ui/views/appwidgets/layouts#anatomy_determining_size) and identify landscape and portrait sizes that your widget may appear on and test for them.\n- If your AppWidget uses `sizeMode == Responsive`, you can set this to one of the sizes from the list that you provide when specifying the `sizeMode`.\n\nThe default duration for a test timeout is 1 second, but you can pass a custom\nduration as an argument to the `runGlanceAppWidgetUnitTest` method if your test\ninfrastructure enforces a different timeout.\n\nFor more information and code samples, see the reference documentation for\n[`runGlanceAppWidgetUnitTest`](/reference/kotlin/androidx/glance/appwidget/testing/unit/package-summary#runGlanceAppWidgetUnitTest(kotlin.time.Duration,kotlin.Function1))."]]