我的單元測試位於集成測試的單獨目錄樹中,但具有相同的包結構。我的集成測試需要外部資源(例如服務器)纔可用,但我的單元測試恰當地相互獨立,並且環境相互獨立。在IntelliJ-IDEA(v7)中,我定義了一個JUnit運行/調試配置來運行頂層包中的所有測試,這當然會發現我的集成測試失敗。在源碼樹中運行所有測試,而不是包
我想定義一個運行所有單元測試的run-junit配置。有任何想法嗎?
我的單元測試位於集成測試的單獨目錄樹中,但具有相同的包結構。我的集成測試需要外部資源(例如服務器)纔可用,但我的單元測試恰當地相互獨立,並且環境相互獨立。在IntelliJ-IDEA(v7)中,我定義了一個JUnit運行/調試配置來運行頂層包中的所有測試,這當然會發現我的集成測試失敗。在源碼樹中運行所有測試,而不是包
我想定義一個運行所有單元測試的run-junit配置。有任何想法嗎?
答案是創建一個測試套件,其中只包含單元測試文件夾下的那些測試,然後運行它。有一個叫做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", "");
}
}
不幸的是,除了在單個模塊中的類和測試類之外,沒有辦法將輸出從IntelliJ編譯中分離出來(它是測試運行器正在查看的類)。
因此,當我進行集成測試時,我只需使用特定於這些測試的第二個模塊來解決此問題,並根據每個模塊的需要指定輸出目錄。
IntelliJ IDEA的CE 10.5有一個(新的?)選項來運行配置的目錄中的所有測試:
是的,這是使用了不同類型的不同模塊的正確方法的測試。在運行/調試配置中,您可以指定將使用哪個模塊類路徑。 – CrazyCoder 2009-08-18 14:25:36
我不能這樣做,項目中已經有多個模塊,並且我們正在爲每個可交付物製造原則開發一個模塊 – 2009-08-18 15:35:56