【问题标题】:Run all tests in a source tree, not a package在源代码树中运行所有测试,而不是在包中
【发布时间】:2010-11-20 14:26:36
【问题描述】:

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

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

我想定义一个运行所有单元测试的 run-junit 配置。有什么想法吗?

【问题讨论】:

    标签: java unit-testing junit intellij-idea


    【解决方案1】:

    答案是创建一个仅包含单元测试文件夹下的那些测试的测试套件,然后运行它。有一个名为DirectorySuiteBuilder 的junit-addon 只是在我重新发明了轮子之后才发现它。

    这里已经有人问过了!

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

    【讨论】:

      【解决方案2】:

      IntelliJ IDEA CE 10.5 有一个(新的?)选项可以在配置的目录中运行所有测试:

      【讨论】:

        【解决方案3】:

        不幸的是,除了通过单个模块中的类和测试类(它是 test runner 正在查看的类)之外,没有办法将输出与 IntelliJ 编译分开。

        因此,当我进行集成测试时,我只需使用特定于这些测试的第二个模块来解决这个问题,并根据需要为每个模块指定输出目录。

        【讨论】:

        • 是的,这是为不同类型的测试使用不同模块的正确方法。在运行/调试配置中,您指定将使用哪个模块类路径。
        • 我做不到,项目中已经有多个模块,我们正在根据可交付工件原则开发一个模块
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-01
        • 1970-01-01
        • 2017-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-12
        相关资源
        最近更新 更多