You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建Gradle任务以运行指定的Espresso测试

Fixing Custom Gradle Task to Run Specific Espresso Test

Got it, let's sort out why your runMyTest task is running all tests instead of just your target Espresso test. The key is to properly configure the task to pass the test class argument to the underlying connectedAndroidTest task, rather than just triggering it without any modifications.

Solution for Groovy DSL (build.gradle)

Add this to your app module's build.gradle file:

task runMyTest {
    // Assign to the "Verification" group so it shows up with other test tasks
    group = "Verification"
    description = "Runs the specific MyTest Espresso test"

    // Before running connectedAndroidTest, set the test class argument
    doFirst {
        connectedAndroidTest.testInstrumentationRunnerArguments.class = 'com.my.tests.MyTest'
    }

    // Make this task depend on connectedAndroidTest so it triggers the test run
    dependsOn connectedAndroidTest
}

How this works:

  • The doFirst block ensures we set the test class argument before connectedAndroidTest executes, overriding any default behavior.
  • By depending on connectedAndroidTest, we reuse the existing test infrastructure (like device setup, APK installation) instead of reinventing the wheel.

If you need to run multiple specific tests, separate them with commas:

connectedAndroidTest.testInstrumentationRunnerArguments.class = 'com.my.tests.MyTest,com.my.tests.AnotherTest'

Solution for Kotlin DSL (build.gradle.kts)

If you're using Kotlin for your Gradle scripts, add this to your app module's build.gradle.kts:

tasks.register("runMyTest") {
    group = "Verification"
    description = "Runs the specific MyTest Espresso test"

    doFirst {
        tasks.connectedAndroidTest.configure {
            testInstrumentationRunnerArguments["class"] = "com.my.tests.MyTest"
        }
    }

    dependsOn(tasks.connectedAndroidTest)
}

Why your original setup didn't work

Chances are your initial custom task was just triggering connectedAndroidTest without modifying its arguments. The default behavior of connectedAndroidTest is to run all instrumented tests unless you explicitly pass the class parameter to narrow it down. This setup ensures the parameter is set every time you run runMyTest.

Verify it works

Run the task with:

./gradlew app:runMyTest

You should see in the output that only com.my.tests.MyTest is executed, not all tests.

内容的提问来源于stack exchange,提问作者netimen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:12:48