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

如何配置SonarQube仅排除测试代码覆盖率,保留其他检测项?

How to Exclude Test Code from Coverage but Keep Quality Checks in SonarQube

Absolutely! You don’t need to use <SonarQubeTestProject>true</SonarQubeTestProject> (which excludes test code from all analyses—coverage, code smells, duplicates, etc.). Instead, you can split your configuration to target only coverage exclusion while retaining quality checks for test code.

Here’s how to do it:

  • First, mark your test code as test sources
    Use the sonar.test.inclusions property to tell SonarQube which files are test code. This doesn’t exclude them from analysis—it just categorizes them correctly. For example:

    sonar.test.inclusions=**/*Test.java,src/test/**/*
    

    Adjust the pattern to match your project’s test file naming convention or directory structure.

  • Then, exclude test code from coverage statistics
    Use the sonar.coverage.exclusions property to exclude those same test files from coverage calculations. This ensures SonarQube skips coverage tracking for test code but still runs all other quality checks (code smells, duplicates, bugs, etc.):

    sonar.coverage.exclusions=**/*Test.java,src/test/**/*
    

Example Configurations by Build Tool

Maven (in pom.xml)

<properties>
  <sonar.test.inclusions>**/*Test.java,src/test/**/*</sonar.test.inclusions>
  <sonar.coverage.exclusions>**/*Test.java,src/test/**/*</sonar.coverage.exclusions>
</properties>

Gradle (in build.gradle)

sonarqube {
  properties {
    property "sonar.test.inclusions", "**/*Test.java,src/test/**/*"
    property "sonar.coverage.exclusions", "**/*Test.java,src/test/**/*"
  }
}

Command Line (using SonarScanner)

sonar-scanner -Dsonar.test.inclusions="**/*Test.java,src/test/**/*" -Dsonar.coverage.exclusions="**/*Test.java,src/test/**/*"

Key Note

Make sure not to set <SonarQubeTestProject>true</SonarQubeTestProject>—this flag tells SonarQube to treat the entire project as a test project, which skips all analysis entirely. The approach above gives you granular control: test code gets full quality analysis, just no coverage stats.

内容的提问来源于stack exchange,提问作者Leow Kah Man

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:01:47