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

前端之家收集整理的这篇文章主要介绍了java – 在源树中运行所有测试,而不是包前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

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

它已经在这里被问到了!

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

猜你在找的Java相关文章