0
我正在使用JUnit,現在我想在運行測試之前執行Java程序(主要方法)。JUnit執行程序@before
I.e.在我的項目中,我有一個包含一個主要方法的類。在我運行我的測試之前,我想運行(也許在一個單獨的進程中),因爲被測試的類將通過套接字連接到他的進程。
我該怎麼做?
最後我想殺掉這個過程當然。
我正在使用JUnit,現在我想在運行測試之前執行Java程序(主要方法)。JUnit執行程序@before
I.e.在我的項目中,我有一個包含一個主要方法的類。在我運行我的測試之前,我想運行(也許在一個單獨的進程中),因爲被測試的類將通過套接字連接到他的進程。
我該怎麼做?
最後我想殺掉這個過程當然。
你幾乎已經回答了你自己。你需要使用任何的Runtime.exec()(http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html)或一些更復雜的工具像「@Before」或註釋,以便阿帕奇百科全書Exec的http://commons.apache.org/proper/commons-exec/index.html
法「@BeforeClass」註釋可以很好地開展在單獨的線程這一過程做這個的地方。最好的方法是將額外的輔助類編程爲單例。只有在以前沒有啓動的情況下,該類纔會負責啓動線程,因此您將只有一個進程用於所有測試。
編輯:應該是這樣的:
@BeforeClass
public static void startProess() throws Exception {
SomeProcess .getInstance().startIfNotRunning();
}
public class SomeProcess {
private Thread thread;
private Process process;
private static SomeProcess instance = new SomeProcess();
public static SomeProcess getInstance() {
return instance;
}
public synchronized void startIfNotRunning() throws Exception {
(...)
// check if it's not running and if not start
(...)
instance.start();
(...)
}
public synchronized void stop() throws Exception {
process.destroy()
}
private synchronized void start() throws Exception {
thread = new Thread(new Runnable() {
@Override
public void run() {
process = Runtime.exec("/path/yo/your/app");
}
});
thread.start();
// put some code to wait until the process has initialized (if it requires some time for initialization.
}
}
但這種方式的程序是作爲一個線程執行,而不是作爲一個過程? – machinery 2014-09-29 10:55:23
你將有一個線程運行獨立的進程。我的意思是它在操作系統中創建新的進程。請參閱[Runtime.exec()]的java文檔(http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec%28java.lang.String%29)。 Runtime.exec()返回一個Process類的實例,該實例連接到在操作系統中啓動的本機進程。您可以使用此返回的Process實例與之通信 - 例如,您可以讀取此進程的控制檯輸出。 – walkeros 2014-09-29 11:08:13
如何殺死JUnit中after子句中的進程? – machinery 2014-09-29 11:35:26