如何在Kotlin中向Android项目添加单元测试?

问题描述 投票:0回答:1

我有一个 Android 项目,我正在尝试添加单元测试。根据 docs,我应该将以下内容添加到我的

build.gradle.kts

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

但是,当我添加时,出现以下错误:

enter image description here

这是我的

build.gradle.kts
。文件:

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()
}

我是 Android 开发新手,所以仍在尝试了解 Gradle 的工作原理。非常感谢任何指导,谢谢。

android kotlin
1个回答
0
投票

该文档适用于 Kotlin/JVMufeff 应用程序。 Android 应用程序需要不同的依赖项来进行本地测试(当您在 Android Studio 中创建新应用程序时默认包含该依赖项):

testImplementation("junit:junit:4.13.2")

这增加了对 JUnit 4 测试的支持。如果您想使用 JUnit Jupiter 进行本地测试,请添加以下内容:

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.3")
}

tasks.withType<Test> {
    useJUnitPlatform()
}
© www.soinside.com 2019 - 2024. All rights reserved.