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

如何使用Gradle命令行运行多个指定分类的测试

多JUnit分类测试执行配置解决方案

失效原因

你当前的配置会将逗号拼接的SmokeTest,StressTest整体作为单个分类类名传入,系统找不到对应类,自然无法匹配到符合要求的测试用例。同时默认的includeCategories仅支持命中任意指定分类就执行的OR逻辑,如果你需要的是同时命中所有指定分类的AND逻辑,还需要额外调整匹配规则。

修复后的build.gradle配置

test {
    useJUnit() {
        if (project.hasProperty("cat")) {
            // 拆分逗号分隔的分类参数,自动补全包名、去除空格
            def targetCategories = project.property("cat").split(",").collect {
                "com.path.to.categories.interfaces.folder.${it.trim()}"
            }
            
            // 场景1:只要命中任意一个指定分类就执行,用以下配置即可
            // includeCategories targetCategories as String[]
            
            // 场景2:必须同时命中所有指定分类才执行(你的需求场景),用以下自定义过滤
            filter {
                eachTest { testDescriptor ->
                    try {
                        // 读取测试类上的Category注解
                        Class testClazz = Class.forName(testDescriptor.className)
                        def categoryAnnos = testClazz.annotations.findAll {
                            it.annotationType().simpleName == "Category"
                        }
                        def testCategoryList = categoryAnnos.collectMany { it.value()*.name }
                        // 校验所有目标分类都被当前测试类标记
                        return targetCategories.every { testCategoryList.contains(it) }
                    } catch (Exception e) {
                        return false
                    }
                }
            }
        }
    }
}

执行命令

和你之前的执行指令完全一致即可:
./gradlew clean test -Pcat=SmokeTest,StressTest

注意事项

  • 请确认配置中分类接口的包前缀com.path.to.categories.interfaces.folder.和你实际项目中分类类的包路径完全一致
  • 如果你的@Category注解是加在测试方法而非测试类上,可在上述过滤逻辑中扩展读取测试方法上的注解即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:09:04