【Kotlin/Android】JUnitのアサーションメソッドの種類
この記事からわかること
- Android Studio/Kotlinで使えるJUnitの使い方
- アサーションメソッドの種類
index
[open]
\ アプリをリリースしました /
友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-
posted withアプリーチ
環境
- Android Studio:Koala
- Kotlin:1.9.0
- JUnit:4
JUnitでのアサーション(検証)
アサーション(Assertion)とは「断言、断定」という意味を持つ英単語でプログラミングにおいては「検証する仕組み」のことを指します。JUnitでも実行結果と期待値を比較検証を行うためのアサーションを行う仕組みが用意されています。
assertEquals(expected: T, actual: T)
期待値と実際の値が等しいかどうかを検証するメソッド。expected
:「期待される」actual
:「実際の〜」
@Test
fun testSample() {
val result = 2 + 3
assertEquals(5, result)
}
assertTrue(condition: Boolean)/assertFalse(condition: Boolean)
条件がtrue/falseであることを検証するメソッド。
@Test
fun testSample() {
val result = 5
assertTrue(result > 0)
}
@Test
fun testSample() {
val result = -3
assertFalse(result > 0)
}
assertNull(object: Any?)/assertNotNull(object: Any?)
引数がnullである/nullでないことを検証するメソッド。
@Test
fun testSample() {
val result: String? = null
assertNull(result)
}
@Test
fun testSample() {
val result: String? = "Hello World"
assertNotNull(result)
}
assertSame(expected: Any, actual: Any)/assertNotSame(expected: Any, actual: Any)
2つのオブジェクトが同一/異なるインスタンスであることを検証するメソッド。
@Test
fun testSample() {
val instance1 = Any()
val instance2 = instance1
assertSame(instance1, instance2)
}
@Test
fun testSample() {
val instance1 = Any()
val instance2 = Any()
assertNotSame(instance1, instance2)
}
まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。
ご覧いただきありがとうございました。