微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 在源树中运行所有测试,而不是包

我的单元测试位于与集成测试不同的目录树中,但具有相同的包结构.我的集成测试需要外部资源(例如服务器)才可用,但我的单元测试正确地相互独立和环境.

在IntelliJ-IDEA(v7)中,我定义了一个JUnit运行/调试配置来运行顶级包中的所有测试,这当然会选择失败的集成测试.

我想定义一个运行所有单元测试的run-junit配置.有任何想法吗?

最佳答案
答案是创建一个测试套件,该套件仅包含单元测试文件夹下的那些测试并运行它.有一个junit-addon就是这个叫做DirectorySuiteBuilder,但是在我重新发明了这个轮子之后我才发现这个.

它已经在这里被问到了!

import junit.framework.JUnit4TestAdapter;
import junit.framework.TestSuite;

import java.io.File;
import java.io.IOException;

public class DirectoryTestSuite {
    static final String rootPath = "proj\\src\\test\\java\\";
    static final ClassLoader classLoader = DirectoryTestSuite.class.getClassLoader();

    public static TestSuite suite() throws IOException,ClassNotFoundException {
    final TestSuite testSuite = new TestSuite();
    findTests(testSuite,new File(rootPath));
    return testSuite;
    }

    private static void findTests(final TestSuite testSuite,final File folder) throws IOException,ClassNotFoundException {
    for (final String fileName : folder.list()) {
        final File file = new File( folder.getPath() + "/" +fileName);
        if (file.isDirectory()) {
        findTests(testSuite,file);
        } else if (isTest(file)) {
        addTest(testSuite,file);
        }
    }
    }

    private static boolean isTest(final File f) {
    return f.isFile() && f.getName().endsWith("Test.java");
    }

    private static void addTest(final TestSuite testSuite,final File f) throws ClassNotFoundException {
    final String className = makeClassName(f);
    final Class testClass = makeClass(className);
    testSuite.addTest(new JUnit4TestAdapter(testClass));
    }

    private static Class makeClass(final String className) throws ClassNotFoundException {
    return (classLoader.loadClass(className));
    }

    private static String makeClassName(final File f) {
    return f.getPath().replace(rootPath,"").replace("\\",".").replace(".java","");
    }
}

原文地址:https://www.jb51.cc/java/438112.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐