2
我有一個運行在Windows 7上的Junit/Silkuli測試,它依賴於已經運行的外部程序。Java/Junit:如何測試外部程序/進程/應用程序是否正在運行?
如何檢查外部程序是否從測試內部運行?
我有一個運行在Windows 7上的Junit/Silkuli測試,它依賴於已經運行的外部程序。Java/Junit:如何測試外部程序/進程/應用程序是否正在運行?
如何檢查外部程序是否從測試內部運行?
您可以在java中運行命令「tasklist」並查看返回的列表以查看您的程序是否在列表中。是這樣的:
String program = "eclipse.exe"; //or any other process
String listOfProcesses = getCommandOutput("tasklist");
if (listOfProcesses == null || listOfProcesses.isEmpty()) {
System.err.println("Unable to automatically determine if " + program + " is running");
} else {
if (listOfProcesses.contains(program)) {
System.out.println(program + " is running!");
} else {
System.out.println(program + " is not running!");
}
}//else: process list can be retrieved
,並使用如方法得到一個命令的輸出:
public static String getCommandOutput(String command) {
String output = null; //the string to return
Process process = null;
BufferedReader reader = null;
InputStreamReader streamReader = null;
InputStream stream = null;
try {
process = Runtime.getRuntime().exec(command);
//Get stream of the console running the command
stream = process.getInputStream();
streamReader = new InputStreamReader(stream);
reader = new BufferedReader(streamReader);
String currentLine = null; //store current line of output from the cmd
StringBuilder commandOutput = new StringBuilder(); //build up the output from cmd
while ((currentLine = reader.readLine()) != null) {
commandOutput.append(currentLine + "\n");
}
int returnCode = process.waitFor();
if (returnCode == 0) {
output = commandOutput.toString();
}
} catch (IOException e) {
System.err.println("Cannot retrieve output of command");
System.err.println(e);
output = null;
} catch (InterruptedException e) {
System.err.println("Cannot retrieve output of command");
System.err.println(e);
} finally {
//Close all inputs/readers
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
System.err.println("Cannot close stream input! " + e);
}
}
if (streamReader != null) {
try {
streamReader.close();
} catch (IOException e) {
System.err.println("Cannot close stream input reader! " + e);
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Cannot close reader! " + e);
}
}
}
//Return the output from the command - may be null if an error occured
return output;
}
乾杯,太棒了! – AlexM 2013-05-01 16:29:59
是外部程序是你自己寫? – 2013-05-01 11:08:40
對於這種情況是的,但也需要爲第三方程序執行此操作。 – AlexM 2013-05-01 12:24:42