Glance 單元測試 API 可讓您在無須加載檢視畫面或 UI 自動化工具的情況下,測試 Glance 程式碼。舉例來說,單元測試 API 可讓您使用 hasContentDescriptionEqualTo
或 isChecked
等比對器驗證條件,例如元素是否列於清單中,或是否已勾選方塊。
這個 API 輕量化且設定較少,因此您可以在開發小工具的個別部分時執行測試導向開發作業,並加以整理,進而改善程式碼重複使用情形。
設定
使用單元測試程式庫所需的依附元件如以下範例所示:
// Other Glance and Compose runtime dependencies.
...
testImplementation 'androidx.glance:glance-testing:1.1.0'
testImplementation 'androidx.glance:glance-AppWidget-testing:1.1.0'
testImplementation 'org.robolectric:robolectric:4.11.1'
...
// You may include additional dependencies, such as Robolectric, if your test
// needs to set a LocalContext.
測試結構
整理 GlanceAppWidget
類別外的可組合函式,以便重複使用程式碼及進行單元測試。請盡可能降低測試中單元的複雜度。
class MyGlanceComposableTest {
@Test
fun myNewsItemComposable_largeSize_hasAuthorAsSubtitle() = runGlanceAppWidgetUnitTest {
// Prepare inputs and state
setAppWidgetSize(100.dp, 100.dp)
// Set the composable under test
provideComposable {
MyNewsItemComposable(TEST_NEWS_ITEM)
}
// Perform assertions
onNode(hasTestTag("subTitle"))
.assertHasText(TEST_NEWS_ITEM.authorName)
}
}
設定測試的情境和大小
如果您的可組合函式使用 LocalContext.current()
方法讀取結構定義,您就必須使用 LocalContext.current()
方法設定結構定義。否則此步驟為選用步驟。
您可以使用任何以 JVM 為基礎的 Android 單元測試架構 (例如 Roboletric) 來提供背景資訊。
如果您的可組合函式存取 LocalSize
,請在測試中提供可組合項之前,先為測試設定目標大小。預設大小為 349.dp x 455.dp,相當於 Pixel 4 裝置上直向模式顯示的 5x4 小工具。
- 如果 AppWidget 使用
sizeMode == Single
,您可以在小工具的info.xml
檔案中將這項參數設為minWidth
和minHeight
。 - 如果 AppWidget 使用
sizeMode == Exact
,則可以採用類似決定小工具大小的方式,找出小工具可能顯示並測試的橫向和直向尺寸, - 如果 AppWidget 使用
sizeMode == Responsive
,就可以將其設為您在指定sizeMode
時所提供的清單中其中一個大小。
測試逾時的預設時間長度為 1 秒,但如果您的測試基礎架構會強制執行不同的逾時,您可以將自訂時間長度做為引數傳遞至 runGlanceAppWidgetUnitTest
方法。
如需詳細資訊和程式碼範例,請參閱 runGlanceAppWidgetUnitTest
的參考說明文件。