2014-09-28 96 views
0

我正在使用JUnit,现在我想在运行测试之前执行Java程序(主要方法)。JUnit执行程序@before

I.e.在我的项目中,我有一个包含一个主要方法的类。在我运行我的测试之前,我想运行(也许在一个单独的进程中),因为被测试的类将通过套接字连接到他的进程。

我该怎么做?

最后我想杀掉这个过程当然。

回答

1

你几乎已经回答了你自己。你需要使用任何的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. 

    } 

} 
+0

但这种方式的程序是作为一个线程执行,而不是作为一个过程? – machinery 2014-09-29 10:55:23

+0

你将有一个线程运行独立的进程。我的意思是它在操作系统中创建新的进程。请参阅[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

+0

如何杀死JUnit中after子句中的进程? – machinery 2014-09-29 11:35:26