[英]Running command line tools inside of a Java program
您好StackOverflow社區,
我有這個JUnit
測試,需要使用命令mvn exec:java
運行服務器,並且我需要在執行測試之前刪除目錄的內容。 否則, JUnit
測試將失敗。 有什么辦法可以將這些步驟包括在我的源代碼中?
埃傑
您應該使用JUnit的@BeforeClass表示法,該表示法將在第一個測試開始之前清理目標目錄。 您還應該使用commons-io庫,避免不必要的編碼。
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.BeforeClass;
import org.junit.Test;
public class DeleteDirectoryTest {
private static final String DIRECTORY_PATH = "C:/TEMP";
@BeforeClass
public static void cleanUp() throws IOException {
FileUtils.deleteDirectory(new File(DIRECTORY_PATH));
}
@Test
public void doSomeTest() {
// Test code goes here
}
}
您可以在JUnit'@BeforeClass'初始化方法中為目錄遞歸刪除 。
public static boolean emptyDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return true;
}
您可以使用ProcessBuilder從Java應用程序執行命令
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.