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

Java如何递归遍历目录所有子目录运行脚本实现全组件JUnit测试

解决思路

  • 调整参数化字段:新增组件路径字段,和测试用例名一起作为参数化传入的值,解决不同组件根目录的定位问题
  • 重构用例扫描逻辑:先遍历根目录Module下所有符合规则的Component子目录,再逐个扫描子目录下的*TEST.tab测试用例文件
  • 移除硬编码配置:测试执行时的基础目录从传入的组件路径动态取值,替换固定写死的Component1/

修改后完整代码

@RunWith(Parameterized.class)
public class ContentTest {
    
    private static final Logger log = LoggerFactory.getLogger(ContentTest.class);
    // 第一个参数:测试用例名
    @Parameter(0)
    public String testCase;    
    // 第二个参数:用例所属的Component路径
    @Parameter(1)
    public String componentPath;

    @Parameters( name = "{index}: {0} (组件:{1})" )
    public static Collection<Object[]> data() {
        FileSystem fs = FileSystems.getDefault();
        // 根目录替换为你的Module实际路径
        Path rootPath = fs.getPath("Module/");
        Set<Object[]> tests = new HashSet<>();
        try {
            PathMatcher testFileMatcher = FileSystems.getDefault().getPathMatcher("glob:**/*TEST.tab");
            // 第一步:先扫根目录下所有Component开头的子目录
            List<Path> componentDirs = Files.list(rootPath)
                    .filter(Files::isDirectory)
                    // 可根据实际Component命名规则调整过滤逻辑,比如匹配正则^Component\d+$
                    .filter(path -> path.getFileName().toString().startsWith("Component"))
                    .collect(Collectors.toList());
            
            // 第二步:逐个Component目录扫描测试用例
            for (Path componentDir : componentDirs) {
                String compPath = componentDir.getFileName().toString() + "/";
                Files.walk(componentDir, FileVisitOption.FOLLOW_LINKS)
                        .filter(testFileMatcher::matches)
                        .map(x -> x.getFileName().toString())
                        .map(fileName -> fileName.substring(0, fileName.length()-4))
                        .forEach(testName -> {
                            // 封装成参数数组:[用例名, 所属组件路径]
                            tests.add(new Object[]{testName, compPath});
                        });
            }
            
            log.info("Going to run the following tests: " );
            tests.stream().map(arr -> arr[1] + arr[0]).forEach(log::info);
            return tests;
        } catch (IOException e) {
            log.error("Could not get testcases.", e);
        }
        return Collections.emptyList();
    }
    
    
    @Test
    public void test1() {
        TestCommand tc = new TestCommand();
        // 动态传入组件路径,不再硬编码
        tc.setBaseDir(new HdfsResource(componentPath));
        List<String> args = new ArrayList<>();
        args.add(testCase);
        args.add("--settings");
        tc.run(args.toArray(new String[args.size()]));
    }   

}

可选优化点

  • 若不同组件存在同名测试用例,可调整@Parameters的name属性,拼接组件名和用例名避免展示重复
  • 可通过配置文件传入根目录路径,无需写死Module/路径
  • 可新增目录过滤规则,排除不需要扫描的Component目录
  • 如需要按组件顺序执行测试,可把存储用例的HashSet换成LinkedHashSet,保证遍历顺序和Component目录排序一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:24:08