facebook twitter hatena line email

Android/kotlin/UnitTest/基本

提供: 初心者エンジニアの簡易メモ
2021年2月5日 (金) 22:25時点におけるAdmin (トーク | 投稿記録)による版

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

テスト作成

一旦プロジェクトをAndroidStudioのkotlinで新規で作る

以下が作られてるので確認。

UnittestApplication/app/src/test/java/com/example/unittestapplication/ExampleUnitTest.kt

package com.example.unittestapplication

import org.junit.Test

import org.junit.Assert.*

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
class ExampleUnitTest {
    @Test
    fun addition_isCorrect() {
        assertEquals(4, 2 + 2)
    }
}

app/src/androidTest/java/com/example/unittestapplication/ExampleInstrumentedTest.kt

package com.example.unittestapplication

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
 * Instrumented test, which will execute on an Android device.
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
    @Test
    fun useAppContext() {
        // Context of the app under test.
        val appContext = InstrumentationRegistry.getInstrumentation().targetContext
        assertEquals("com.example.unittestapplication", appContext.packageName)
    }
}

テスト実行

プロジェクト直下で実行

# ローカル単体テスト(tests側)
$ ./gradlew test
34 actionable tasks: 20 executed, 14 up-to-date
# インストゥルメント化単体テスト(androidTests側)
$ ./gradlew connectedAndroidTest
50 actionable tasks: 30 executed, 20 up-to-date

公式参考:https://developer.android.com/studio/test/command-line?hl=ja#AMOptionsSyntax

tests側

結果出力先 app/build/reports/tests/testDebugUnitTest/index.html

問題ないとき

以下のように出力されてた

addition_isCorrect	0.001s	passed

間違えたとき

以下のようにコードを変更

assertEquals(5, 2 + 2)

実行後レポートには、以下のように出力されてた。

java.lang.AssertionError: expected:<5> but was:<4>

個別メソッドのテスト

AndroidStudioで、ExampleUnitTest.ktを選択し、副クリックで、runすると個別メソッドをテストできる。

参考

https://qiita.com/nozaki-sankosc/items/538fe9b2a13aa7403df6