gpt4 book ai didi

java - JUnit @before 执行程序

转载 作者:行者123 更新时间:2023-12-01 12:29:11 29 4
gpt4 key购买 nike

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

即在我的项目中,我有一个包含一个具有 main 方法的类的包。我想在运行测试之前运行它(可能在一个单独的进程中),因为被测试的类将通过套接字连接到他的进程。

我怎样才能做到这一点?

最后我当然想终止这个进程。

最佳答案

你几乎已经回答了自己。您需要使用 Runtime.exec() ( http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html ) 或一些更复杂的工具(例如 Apache Commons Exec http://commons.apache.org/proper/commons-exec/index.html )在单独的线程中启动此进程。

使用“@Before”或“@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.

}

}

关于java - JUnit @before 执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085096/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com