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","");
    }
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...