首页 > 解决方案 > 如何在junit集成测试期间启动/停止java应用程序

问题描述

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

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

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

标签: javajunit

解决方案


我无法用 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();  
    }
}

推荐阅读