[英]How to start/stop java application during junit integration test
我已经做了相当多的研究,并没有看到一个好的方法来做到这一点。 我有一个具有集成测试的 java 应用程序。 为了集成测试,测试需要启动实际应用程序。 这在每个 junit 测试中都是这样做的。
@BeforeClass
final public static void setup() {
Application.main(new String[]{});
}
我如何关闭应用程序? 我注意到在 junit 测试关闭后,它仍然作为流氓进程存在。 另外我之前用springboot做过这个,并且知道springboot提供了注释。 我们不能为此使用springboot。 所以我需要找到一种非 spring 方式。 如何在 junit 测试中关闭应用程序?
我无法用 Gradle 6.3 和 JUnit 5 重现此问题; 我在ps
output 中简要地看到了一个[java] <defunct>
进程,它会自行消失。 也许是因为我只运行一个测试套件,当您运行更多时,您需要在每个测试套件之后进行清理。
也就是说,查看Java 进程 API 。 按照这个问题启动应用程序,但保留从ProcessBuilder.start()
返回的Process
并在您的@AfterClass
方法中调用它的destroy()
方法。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.