[英]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.