Java JUnit执行程序@before
我正在使用JUnit,现在我想在运行测试之前执行一个Java程序(main方法) 也就是说,在我的项目中,我有一个包,其中包含一个具有main方法的类。在我运行测试之前,我想运行它(可能在一个单独的进程中),因为被测试的类将通过套接字连接到他的进程 我该怎么做Java JUnit执行程序@before,java,junit4,Java,Junit4,我正在使用JUnit,现在我想在运行测试之前执行一个Java程序(main方法) 也就是说,在我的项目中,我有一个包,其中包含一个具有main方法的类。在我运行测试之前,我想运行它(可能在一个单独的进程中),因为被测试的类将通过套接字连接到他的进程 我该怎么做 最后,我当然想结束这个过程。你几乎回答了自己的问题。您需要使用Runtime.exec()或其他更复杂的工具(如ApacheCommonsExec)在单独的线程中启动此进程 使用“@Before”或“@BeforeClass”注释注释的方
最后,我当然想结束这个过程。你几乎回答了自己的问题。您需要使用Runtime.exec()或其他更复杂的工具(如ApacheCommonsExec)在单独的线程中启动此进程 使用“@Before”或“@BeforeClass”注释注释的方法可以很好地执行此操作。最好的方法是将额外的helper类编程为singleton。这个类将只负责在之前没有启动线程的情况下启动线程,因此所有测试只有一个进程
编辑:它应该类似于:
@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.
}
}
但通过这种方式,程序是作为线程而不是进程执行的?您将有一个线程,它将运行单独的进程。我的意思是它在操作系统中创建了新的进程。请参阅的java文档。Runtime.exec()返回连接到操作系统中启动的本机进程的进程类实例。您可以使用此返回的流程实例与之通信-例如,您可以读取此流程的控制台输出。如何在JUnit中的after子句中终止该流程?存储Runtime.exe()返回的流程实例(我根据此编辑了该示例)。稍后只需调用process.destroy()。我再次编辑以创建stop()方法。所以在@AfterClass上调用SomeProcess.getInstance().stop()非常感谢。这个新进程是否创建了一个新的JVM实例?就像从命令行启动程序一样。