Android Compose Hilt with test

사용 언어: Kotlin 1.9.0
사용 버전: Android Studio Hedgehog 2023.1.1 Patch 1


안드로이드 컴포즈 Hilt with test를 알아보겠습니다.



Hilt는 DI(Dependency Injection, 의존성 주입)를 편하게 하기 위한 라이브러리입니다.
Dagger라는 DI 라이브러리를 Android에 사용하기 편하게 수정한 게 Hilt입니다.


이번 시간에는 Hilt를 사용하여 UI test, unit test를 하는 방법을 알아보겠습니다.




공식 사이트입니다.
https://dagger.dev/hilt/



Android Compose Hilt 게시글과 이어집니다.





test(테스트)를 위해서는 dependency(의존성) 설정이 필요합니다.



우리는 UI test와 unit test를 진행하기 때문에 이 부분을 app 용 build.gradle에 추가합니다.

// For instrumentation tests

androidTestImplementation("com.google.dagger:hilt-android-testing:2.50")

kaptAndroidTest("com.google.dagger:hilt-compiler:2.50")


// For local unit tests

testImplementation("com.google.dagger:hilt-android-testing:2.50")

kaptTest("com.google.dagger:hilt-compiler:2.50")




Sync Now를 누릅니다.







Unit test는 딱히 달라질 건 없습니다.

그대로 실행됩니다.

AmphibiansViewModelTest.kt

NetworkAmphibiansRepositoryTest.kt






UI test에서 Hilt를 사용하기 위해서는 3가지 작업이 필요합니다.







@HiltAndroidTest, @get:Rule(order)를 추가해 줍니다.

order는 Rule이 두 개 이상일 때 필요합니다.

AmphibiansAppScreenTest.kt







Android Instrumentation test를 위해서는 test runner가 필요합니다.





app 용 build.gradle로 갑니다.

androidTestImplementation("androidx.test:runner:1.5.2")






CustomtestRunner.kt를 만듭니다.






아래와 같이 AndroidJUnitRunner를 상속받은 class를 만들고 newApplication을 override 합니다.

HiltTestApplication::class.java.name을 넣어줍니다.

CustomTestRunner.kt







createComposeRule을 createAndroidcomposeRule<MainActivity>로 변경해 줍니다.

@Before에 hiltRule.inject()를 해주고, composeTestRule.activity.setContent를 해줍니다.

AmphibiansAppScreenTest.kt






테스트해봅시다.





잘 되네요.



이렇게, Manual Dependency Injection(수동 의존성 주입)의 Unit test, UI test에 Hilt 적용을 해보았습니다.





끝.



카테고리: Android, Compose

댓글

이 블로그의 인기 게시물

Python urllib.parse.quote()

Python bytes.fromhex()

Python OpenCV 빈 화면 만들기

Android Notification with Full Screen

Android Minimum touch target size

Android Compose Instrumentation test to unit test

KiCad 시작하기 7 (FreeRoute 사용하기 2)

tensorflow tf.expand_dims()

딩기 요트 명칭

Android AVD Ram size change