如何配置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 thesonar.test.inclusionsproperty 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 thesonar.coverage.exclusionsproperty 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

