简体   繁体   English

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

[英]How to start/stop java application during junit integration test

I have done a fair amount of research and don't see a good way to do this.我已经做了相当多的研究,并没有看到一个好的方法来做到这一点。 I have a java application that has integration tests.我有一个具有集成测试的 java 应用程序。 For the sake of the integration tests, the tests need to start the actual application.为了集成测试,测试需要启动实际应用程序。 This is done like so in each junit test.这在每个 junit 测试中都是这样做的。

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

How do I shut down the application though?我如何关闭应用程序? I notice it stays around as rogue process after the junit tests shutdown.我注意到在 junit 测试关闭后,它仍然作为流氓进程存在。 In addition I have done this with springboot before and am aware that springboot provides annotations.另外我之前用springboot做过这个,并且知道springboot提供了注释。 We cannot use springboot though for this.我们不能为此使用springboot。 So i need to find a non spring way.所以我需要找到一种非 spring 方式。 How do I shut down the application in a junit test?如何在 junit 测试中关闭应用程序?

I cannot reproduce this with Gradle 6.3 and JUnit 5;我无法用 Gradle 6.3 和 JUnit 5 重现此问题; I briefly see a [java] <defunct> process in the ps output, and that disappears on its own.我在ps output 中简要地看到了一个[java] <defunct>进程,它会自行消失。 Maybe it's because I only run a single test suite and when you run more you'd need to cleanup after each.也许是因为我只运行一个测试套件,当您运行更多时,您需要在每个测试套件之后进行清理。

That said, look into the Java process API .也就是说,查看Java 进程 API Start the app as in this question , but hold on to the Process returned from ProcessBuilder.start() and call its destroy() method in your @AfterClass method.按照这个问题启动应用程序,但保留从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM