0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Android】Android テストの分類(Unit Test / Instrumented Test / UI Test)

Posted at

はじめに

Android 開発でよく使われる 3種類のテストUnit Test・Instrumented Test・UI Test ― の特徴と使い分けを解説します。


1. Unit Test(単体テスト)

特徴

  • 実行環境:JVM(Android 端末不要)
  • 対象:ビジネスロジック、ユーティリティクラス、ViewModel
  • 速度:高速(秒単位で実行可能)
  • 目的:小さな単位での正しさを保証

よく使うライブラリ

  • JUnit4 / JUnit5:テストフレームワーク
  • Mockito / MockK:モック化
  • Truth / AssertJ:アサーション

サンプル

class Calculator {
    fun add(a: Int, b: Int) = a + b
}

class CalculatorTest {
    private val calculator = Calculator()

    @Test
    fun add_twoNumbers_returnsSum() {
        assertEquals(4, calculator.add(2, 2))
    }
}

2. Instrumented Test(計測テスト)

特徴

  • 実行環境:Android 実機またはエミュレータ
  • 対象:Android Framework に依存する処理
    • Context, SharedPreferences, Room DB, Resources など
  • 速度:やや遅い(エミュレータ起動が必要)
  • 目的:実機環境に依存するコードの検証

サンプル

@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
    @Test
    fun useAppContext() {
        val context = InstrumentationRegistry.getInstrumentation().targetContext
        assertEquals("com.example.app", context.packageName)
    }
}

3. UI Test(ユーザーインターフェーステスト)

特徴

  • 実行環境:Android 実機またはエミュレータ
  • 対象:画面遷移、ユーザー操作(クリック、入力、スクロール)
  • 目的:ユーザー視点での操作確認、自動化による回帰防止

フレームワーク

  • Espresso(Google公式、アプリ内 UI テスト)
  • UI Automator(システム UI や別アプリも対象にできる)

サンプル(Espresso)

@Test
fun buttonClick_changesText() {
    onView(withId(R.id.button))
        .perform(click())

    onView(withId(R.id.textView))
        .check(matches(withText("Clicked!")))
}

4. テストの位置づけ(テストピラミッド)

テストの数と役割を表すモデルとして テストピラミッド がよく使われます。

    UI テスト(少量・遅い)
   ------------------------
   Instrumented Test(中量)
   ------------------------
   Unit Test(大量・高速)
  • Unit Test:基盤を支える大量・高速なテスト
  • Instrumented Test:環境依存を補う
  • UI Test:重要なユーザーフローを担保

まとめ

  • Unit Test:ロジックを高速に検証
  • Instrumented Test:Android 環境依存部分を確認
  • UI Test:ユーザー操作を自動で確認

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?