LoginSignup
1
0

Hiltで単体テスト

Last updated at Posted at 2024-03-07

Androidで、DIで注入した場合にそのメソッドを単体テスト(ユニットテスト)を実施することがあるのですが、情報が正確に記載されてる記事があまりなかったので、記事にしたいと思います。
本来は、Junit5を使いたいのですが、HiltがJunit4を前提にしているため使えませんでした。
そのための制約が色々ありました。

Gradle

  • junit
    @Ruleを使用するために必要

  • androidx.junit
    AndroidJUnit4::classを使用するために必要

  • robolectric
    @Configを使用するために必要

testImplementation("junit:junit:4.13.2")
testImplementation("androidx.test.ext:junit-ktx:1.1.5")
testImplementation("org.robolectric:robolectric:4.11.1")
testImplementation("com.google.dagger:hilt-android-testing:2.50")
kaptTest("com.google.dagger:hilt-android-compiler:2.50")

テストコード

@Singleton
SampleRepository {
    fun checkInteger(value: Int): Boolean {
        if (value > 0) {
            return true
        }
        return false
    }
}
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
@RunWith(AndroidJUnit4::class)
class SampleTest {

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @Inject
    lateinit var sampleRepository: SampleRepository

    @Before
    fun setUp() {
        hiltRule.inject()
    }

    @Test
    fun `整数テスト001`() {
        val result = sampleRepository.checkInteger(100)
        assertTrue(result)
    }
    
    @Test
    fun `整数テスト002`() {
        val result = sampleRepository.checkInteger(-1)
        assertFalse(result)
    }
}

ポイントとしては、下記を定義することなのですが、上記のtestImplementationとの繋がりが分かりづらいです。

@HiltAndroidTest
@Config(application = HiltTestApplication::class)
@RunWith(AndroidJUnit4::class)

@get:Rule
  • @HiltAndroidTest
    hilt-android-testing

  • @Config
    robolectric

  • @RunWith(AndroidJUnit4::class)
    androidx.junit

  • @get:Rule
    junit

それぞれ、別々のライブラリーを必要としているのとどのライブラリーが何を提供しているか分かりづらいのでまとめてみました。

まとめ

Junit5を使いたいのですが、Googleが全く興味を示していないため絶望的だと思います。
なので、今回のJunit4を使っていきましょう。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0