Glance 단위 테스트 API를 사용하면 뷰를 인플레이션하거나 UI Automator가 필요하지 않고도 Glance 코드를 테스트할 수 있습니다. 예를 들어 단위 테스트 API를 사용하면 hasContentDescriptionEqualTo 또는 isChecked와 같은 매처를 사용하여 요소가 목록에 있는지 또는 상자가 선택되었는지와 같은 조건을 확인할 수 있습니다.
이 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.
테스트 구조
코드 재사용과 단위 테스트를 지원하려면 GlanceAppWidget 클래스 외부에서 컴포저블 함수를 정리하세요. 테스트 중인 단위의 복잡성을 최대한 줄입니다.
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)}}
테스트의 컨텍스트 및 크기 설정
컴포저블 함수가 LocalContext.current() 메서드를 사용하여 컨텍스트를 읽는 경우 setContext()를 사용하여 컨텍스트를 설정해야 합니다. 그렇지 않으면 이 단계는 선택사항입니다.
Robolectric과 같은 JVM 기반 Android 단위 테스트 프레임워크를 사용하여 컨텍스트를 제공할 수 있습니다.
컴포저블 함수가 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 메서드에 맞춤 지속 시간을 인수로 전달할 수 있습니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-21(UTC)
[[["이해하기 쉬움","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(UTC)"],[],[],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))."]]