Android Compose Instrumentation test to unit test

사용 버전: Android Studio Jellyfish 2023.3.1

안드로이드 컴포즈 Instrumentation test to unit test를 알아보겠습니다.


Instrumentation(계측) test(테스트)라고 하면, 보통 UI(유아이) test를 말합니다. Unit(유닛) test는 보통 코드의 로직을 test 할 때 사용합니다.
Instrumentation test의 단점은 emulator(에뮬레이터)나 실제 device(장치)가 있어야 한다는 점인데요. 이는 테스트의 속도를 떨어뜨리게 됩니다.
이러한 Instrumentation test를 emulator 없이 실행할 수 있게 해주는 것이 있습니다. 바로 Robolectric(로보레트릭)입니다.
https://robolectric.org


이처럼 Unit test처럼 test 할 수 있게 해줍니다.





적용해 봅시다.







앱 용 Build.gradle로 갑니다.
testOptions를 적어주고, unitTests 그리고 isIncludeAndroidResources를 true로 만들어 줍니다.







libs.versions.toml
robolectric을 정의합니다.









그리고 testImplementation을 적어줍니다.








여러분 프로젝트에 libs.versions.toml을 사용하지 않는다면, 예시처럼 org.robolectric:robolectric:4.12를 적어주시면 됩니다.

자, 그러면 이제 context가 필요해서 androdTest로 만들었던 것들을 그냥 test로 옮길 수 있게 됩니다.








옮길 대상은 database와 repository입니다.

unitTest로 옮겨졌네요.







그다음 해야 할 것을 문서에서 보면, 아래처럼 RunWith를 추가해 주는 것입니다.
RunWith(RobolectricTestRunner.class)









옮겨온 test class 위에 적어줍니다.










그리고 기존에 context를 가져오는 코드를 변경합니다.








RuntimeEnvironment.getApplication().applicationContext로 가져옵니다.








자, 실행해 봅시다.
테스트가 잘 성공했네요.










끝.


카테고리: Android

댓글

이 블로그의 인기 게시물

Python urllib.parse.quote()

KiCad 시작하기 4 (기존 회로도 수정 및 추가)

Android Compose Coil library

KiCad 시작하기 1 (회로도 만들기)

Android Notification with Full Screen

iOS Swift callAsFunction

Forensics .pyc 파일 .py로 복구하기

iOS Error Undefined symbol Testing.Trait

Android Custom IME(Input method editor) 만들기

Android Compose automation for getting localized images to use on Play Store app image