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

Android Gradle中使用Jacoco生成覆盖率报告时如何筛选测试用例

How to Generate Jacoco Coverage Reports for Filtered Instrumented Tests

Alright, let's break down how to fix this— the core issue here is that Jacoco's coverage report task doesn't natively support the --tests parameter, since it’s an aggregation task that relies on the results of a prior test run. Here’s how to get both filtered tests and coverage reports working together:

Solution 1: Run Filtered Tests + Coverage Report in One Command

You can chain two Gradle tasks together. First execute the instrumented test task with your --tests filter, then run the coverage report task. Gradle executes tasks in order, so the report will automatically use the results from your filtered test run.

Replace <YourPackage> with your actual package name (e.g., MyApp) and use this command:

./gradlew connected<YourPackage>DebugAndroidTest --tests "com.myproject.test.*" create<YourPackage>DebugAndroidTestCoverageReport

Why this works:

  • connected<YourPackage>DebugAndroidTest is the task that runs your instrumented tests (from the androidTest directory) on a connected device/emulator. This task does support the --tests flag to filter test cases.
  • After the filtered tests finish, the create...CoverageReport task generates the report using the test execution data from that run— so only coverage from your specified tests will be included.

Solution 2: Configure Fixed Test Filters in Build.gradle

If you regularly run the same subset of tests for coverage, you can hardcode the filter in your module’s build.gradle file to avoid typing the --tests flag every time:

android {
    // ... your existing configuration

    testOptions {
        androidTests.all {
            // Filter instrumented tests to only include your target package/class
            filter {
                includeTestsMatching "com.myproject.test.*"
            }
        }
    }

    buildTypes {
        debug {
            testCoverageEnabled true // Ensure this is enabled for debug builds
        }
    }
}

Then you can run the coverage report task directly, and it will use your pre-configured filtered tests:

./gradlew create<YourPackage>DebugAndroidTestCoverageReport

Key Notes to Avoid Confusion:

  • Don’t mix up test and connectedAndroidTest: The test task runs unit tests from the test directory, while connectedAndroidTest runs instrumented tests from androidTest (which is what you’re targeting here). Your initial test --tests command worked for unit tests, but it doesn’t affect instrumented test coverage.
  • Ensure a device or emulator is connected before running the command, or set up Gradle Managed Devices to automate device provisioning.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:05:09