JUnit 5 通过 @Tag 注解实现测试分类,配合构建工具(如 Maven Surefire、Gradle)或 IDE 的标签过滤功能可定向执行测试;@Tag 用于标记类或方法,标签名需符合 Java 标识符规范且大小写敏感。

JUnit 5 提供了基于标签(@Tag)的测试分类机制,配合 @IncludeTags(实际是构建工具或运行时配置中的过滤参数)可实现灵活的分组与定向执行。注意:@IncludeTags 并非 JUnit 内置注解,而是 Maven Surefire / Gradle Test 等插件支持的运行时过滤选项;真正用于标记测试的是 @Tag,而筛选逻辑由测试运行器或构建工具完成。
用 @Tag 给测试方法或类打标签
@Tag 是 JUnit 5 的标准注解,可用于类或方法级别,支持字符串值(不能含空格、逗号、冒号等特殊字符)。多个标签可用多个 @Tag 注解叠加。
- 给单个测试方法加标签:
@Test
@Tag("smoke")
@Tag("api")
void shouldCreateUser() {
// ...
}- 给整个测试类加标签(该类下所有
@Test方法默认继承这些标签):
@Tag("integration")
class UserServiceIntegrationTest {
@Test
void shouldLoadUserById() { /* ... */ }
<pre class="brush:php;toolbar:false;">@Test
@Tag("slow") // 可覆盖/补充类级标签
void shouldSyncWithExternalService() { /* ... */ }}
在 Maven 中按标签过滤运行(使用 surefire 插件)
Maven Surefire 插件通过 <includes></includes> 或更常用的是 <groups></groups> 参数支持标签过滤(对应 JUnit 的 @Tag),实际生效的是 groups 配置项。
立即学习“Java免费学习笔记(深入)”;
- 只运行带
smoke标签的测试:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<groups>smoke</groups>
</configuration>
</plugin>- 运行多个标签(逻辑 OR):
<groups>smoke,integration</groups>
- 排除某类标签(需配合
<excludes></excludes>或使用!tag语法,取决于 Surefire 版本;推荐用groups+excludedGroups):
<groups>api</groups> <excludedGroups>slow</excludedGroups>
在 Gradle 中按标签过滤运行
Gradle 的 test 任务原生支持 includeTags 和 excludeTags 属性(自 Gradle 4.6+,JUnit Platform 集成后)。
- 命令行只运行
smoke标签的测试:
./gradlew test --tests "*smoke*"
更规范的方式是在 build.gradle 中配置:
test {
useJUnitPlatform {
includeTags = ["smoke", "api"]
excludeTags = ["slow"]
}
}- 运行时动态指定(推荐 CI 场景):
./gradlew test -Dtags=smoke
再配合 systemProperty 读取并设置:
test {
systemProperty "junit.platform.tags", System.getProperty("tags", "")
useJUnitPlatform()
}IDE 中运行指定标签的测试(IntelliJ IDEA 示例)
IntelliJ 原生支持 JUnit 5 标签过滤:
- 右键点击测试类或方法 → Run 'xxx' with Coverage → 在弹出窗口中点击齿轮图标 → Modify Options → Tags → 输入
smoke或api - 也可直接在运行配置的 VM Options 中添加:
-Djunit.platform.tags=smoke - 编辑运行配置时,勾选 JUnit Platform,并在 Tags 输入框填写标签名(支持逗号分隔)
这样就能在开发阶段快速验证某类测试,无需修改代码或构建脚本。
不复杂但容易忽略:标签名是纯字符串匹配,大小写敏感,且必须符合 Java 标识符规范(建议全小写、用短横线分隔如 db-integration,但注意 JUnit 要求不能含短横线——所以推荐用下划线 db_integration 或驼峰 dbIntegration)。


















