androidkotlin

How to add unit tests to Android project in Kotlin?


I have an Android project and I'm trying to add unit tests. As per the docs I should add the following to my build.gradle.kts:

dependencies {
    // Other dependencies.
    testImplementation(kotlin("test"))
}
tasks.test {
    useJUnitPlatform()
}

However, when I add that I get the following errors:

enter image description here

This is my build.gradle.kts. file:

plugins {
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.kotlinAndroid)
    alias(libs.plugins.compose.compiler)
}

android {
    namespace = "com.example.myapp"
    compileSdk = 34
    defaultConfig {
        applicationId = "com.example.myapp"
        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"
    }
    buildFeatures {
        compose = true
    }
    packaging {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
    buildTypes {
        getByName("release") {
            isMinifyEnabled = false
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {
    implementation(projects.shared)
    implementation(libs.compose.ui)
    implementation(libs.compose.ui.tooling.preview)
    implementation(libs.compose.material3)
    implementation(libs.androidx.activity.compose)
    implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1")
    implementation("androidx.activity:activity-compose:1.8.0")
    debugImplementation(libs.compose.ui.tooling)
    testImplementation(kotlin("test"))
}

tasks.test {
    useJUnitPlatform()
}

I'm new to Android development so still trying to understand how Gradle works. Any guidance much appreciated, thank you.


Solution

  • That documentation is for Kotlin/JVM apps. An android app requires different dependency for local tests (which is included by default when you create a new app in android studio):

    testImplementation("junit:junit:4.13.2")
    

    This adds support for JUnit 4 tests. If you want to use JUnit Jupiter for your local tests, add this instead:

    dependencies {
        testImplementation("org.junit.jupiter:junit-jupiter:5.10.3")
    }
    
    tasks.withType<Test> {
        useJUnitPlatform()
    }
    

    There is also this 3rd party plugin that allows to use JUnit 5 in Android apps.