LoginSignup
0
0

以前、Androidでの単体テストを投稿しました。
その際、アサーションはJunitのものを使っていました。

今回は、Googleが提供しているTruthを使ってみたいと思います。

導入

testImplementation("com.google.truth:truth:1.4.2")
// Android用
testImplementation("androidx.test.ext:truth:1.5.0")

実装

@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)
        assertThat(result).isTrue()
    }
    
    @Test
    fun `整数テスト002`() {
        val result = sampleRepository.checkInteger(-1)
        assertThat(result).isFalse()
    }
}

比較

  • JUnitの場合、検証した結果を事前に想定してアサーションを用意しないといけません
assertTrue(result)
  • Truthの場合、assertThatにオブジェクトを渡すとそのオブジェクトに対しての検証内容を決めることが出来ます
assertThat(result).isTrue()

例えば、文字列を検証したい場合は、assertThatに文字列を渡すと何を検証出来るか分かるようになっています。

スクリーンショット 2024-03-27 15.41.34.png

assertThat("string").isEqualTo("string")

// 下記は、エラーとなります。
assertThat("string").isTrue()
  • 数値の場合、このような検証も出来ます。JUnitでは、一致検証のみなので、このような検証は難しいです
// numberは、10より大きい
val number = 100
assertThat(number).isGreaterThan(10)

まとめ

JUnitのアサーションでも問題ありませんが、直感的にアサーションが出来るTruthは、便利だと思います。
Android以外にJavaでもアサーション出来ますので、楽しい単体テストを作ってみてください。

0
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
0
0