我已经进行了大量研究,但没有找到一种很好的方法。我有一个具有集成测试的Java应用程序。为了进行集成测试,测试需要启动实际的应用程序。就像在每个junit测试中一样。
@BeforeClass
final public static void setup() {
Application.main(new String[]{});
}
但是我如何关闭该应用程序?我注意到在junit测试关闭后,它仍然作为流氓进程存在。另外,我之前使用springboot做到了这一点,并且知道springboot提供了注释。我们不能为此使用springboot。所以我需要找到一种非春季的方式。如何在junit测试中关闭应用程序?
我无法使用Gradle 6.3和JUnit 5复制它;我在[java] <defunct>
输出中简要看到了ps
进程,该进程自行消失了。也许是因为我只运行一个测试套件,而当您运行更多测试套件时,则需要在每个套件之后进行清理。
也就是说,查看Java process API。如this question中所示启动应用程序,但请保留从Process
返回的ProcessBuilder.start()
,并在destroy()
方法中调用其@AfterClass
方法。
package com.example.demo;
import java.util.ArrayList;
import org.junit.jupiter.api.*;
public class DemoApplicationTests {
private static Process process;
@BeforeAll
public static void beforeClass() throws Exception {
ArrayList<String> command = new ArrayList<String>();
command.add(System.getProperty("java.home") + "/bin/java"); // quick and dirty for unix
command.add("-cp");
command.add(System.getProperty("java.class.path"));
command.add(DemoApplication.class.getName());
ProcessBuilder builder = new ProcessBuilder(command);
process = builder.inheritIO().start();
}
@Test
void whatever() {
// ...
}
@AfterAll
public static void afterClass() {
process.destroy();
}
}