gpt4 book ai didi

java - 如何在junit集成测试期间启动/停止java应用程序

转载 作者:行者123 更新时间:2023-12-01 16:54:13 26 4
gpt4 key购买 nike

我已经做了相当多的研究,但没有找到一个好的方法来做到这一点。我有一个具有集成测试的java应用程序。为了进行集成测试,测试需要启动实际应用程序。在每个 junit 测试中都是这样完成的。

@BeforeClass
final public static void setup() {
Application.main(new String[]{});
}

我如何关闭该应用程序?我注意到在 junit 测试关闭后它仍然作为流氓进程存在。另外我之前用springboot做过这个,并且知道springboot提供了注释。但我们不能为此使用 springboot。所以我需要找到一种非 Spring 的方式。如何在 junit 测试中关闭应用程序?

最佳答案

我无法使用 Gradle 6.3 和 JUnit 5 重现此问题;我简单地看到了一个[java] <defunct>进程在 ps输出,然后它会自行消失。也许是因为我只运行一个测试套件,当您运行更多测试套件时,您需要在每个测试套件之后进行清理。

也就是说,请查看 Java process API 。启动应用程序,如this question ,但请保留 ProcessProcessBuilder.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();
}
}

关于java - 如何在junit集成测试期间启动/停止java应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61622683/

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