在源树中运行所有测试,而不是包 [英] Run all tests in a source tree, not a package

查看:74
本文介绍了在源树中运行所有测试,而不是包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My unit tests are in a separate directory tree from my integration tests, but with the same package structure. My integration tests need external resources (e.g. a server) to be available, but my unit tests are properly independent of each other and the environment.

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

In IntelliJ-IDEA (v7) I have defined a JUnit Run/Debug Configuration to run all the tests in the top-level package, and this of course picks up my integration tests which fail.

I想要定义运行所有单元测试的run-junit配置。有什么想法?

I want to define a run-junit configuration that runs all my unit tests. Any ideas?

推荐答案

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

The answer is to create a test suite that contains only those tests underneath the unit test folder and run that instead. There is a junit-addon which does just this called DirectorySuiteBuilder but I only found this after I had pretty much re-invented the wheel.

这里已经有人问过了!

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

这篇关于在源树中运行所有测试,而不是包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆