17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

KotlinAndroid で JUnit4 Testを書く

Posted at

設定

build.gradleにKotlinとAndroidTestの設定を入れる。

build.gradle
buildscript {
    ext.kotlin_version = '0.12.613'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "me.mattak.kotlinandroidtestsample"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test:rules:0.3'
}

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" を忘れがちなので注意。

com.android.support.test パッケージを使うとJUnit4サポートが簡単。

Test

ApplicationTest.kt
package me.mattak.kotlinandroidtestsample

import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit
import org.junit.runner.RunWith
import kotlin.test.assertEquals

/**
 * ApplicationTest
 */
RunWith(AndroidJUnit4::class)
public class ApplicationTest {
    junit.Before
    public fun setup() {
        // something setup
    }

    junit.After
    public fun teardown() {
        // something teardown
    }

    junit.Test
    public fun packageName() {
        assertEquals(InstrumentationRegistry.getTargetContext().getPackageName(), "me.mattak.kotlinandroidtestsample")
    }
}

RunWith(AndroidJUnit4::class) してあげる点と、junit.Testのアノテーションをつける点を忘れなければ大丈夫。

Context は JUnit4から InstrumentationRegistry.getTargetContext() から取るようになったようだ。

SampleCode

KotlinAndroidTestSample

確認にどうぞ。./gradlew connectedCheck --info で実行できます。

17
18
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
17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?