java - 如何在junit集成测试期间启动/停止java应用程序
问题描述
我已经做了相当多的研究,并没有看到一个好的方法来做到这一点。我有一个具有集成测试的 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 进程 API。像在这个问题中一样启动应用程序,但保留Process
返回的 from并在您的方法中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();
}
}
推荐阅读
- crystal-reports - 水晶报表页码
- android - 用于检索数据的 SQLite 查询 Order By
- javascript - 限制用户对消息的反应
- algorithm - 竞争性编程 - 使用 P、Q 和 R 成分准备完美的咖喱
- xml - 使用 XSD 验证 XML。错误:架构无效或缺少命名空间
- android - 当设备安装在移动的车辆上时,Compass App Roll/Y 值不变
- java - 如何从 RabbitMQ 的队列中删除消息
- python - Json.loads() 和 json.load() 不解析我的文件
- django - Django 如何回滚或检索字段中的数据?
- spring - How to stop polling after a message is received? Spring Integration