简体   繁体   English

Junit5 无法在测试中执行 shell 命令

[英]Junit5 is unable to execute shell commands within tests

I had question about running scripts using Junit 5. I have the following piece of code:我对使用 Junit 5 运行脚本有疑问。我有以下代码:

public class RunMvnSubprocess {
    @Test
    public void main() throws IOException, InterruptedException {
        String[] cmd = new String[]{"mvn.cmd", "-version"}; // command to be executed on command prompt.
        Process p = Runtime.getRuntime().exec(cmd);
        try (BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            while ((line = output.readLine()) != null) {
                System.out.println(line);
            }
        }
        p.waitFor();
    }
}

I get no output when I run it using Junit 5.7.0.当我使用 Junit 5.7.0 运行它时,我没有得到任何输出 However, running this on Junit 4.13.2 works fine.但是,在 Junit 4.13.2 上运行它可以正常工作。

Please note that I am running this piece of test in Windows 10 Pro version 21H1.请注意,我在 Windows 10 专业版 21H1 中运行此测试。

EDIT:编辑:

Modifying修改

new String[]{"mvn.cmd", "-version"}

to

new String[]{"cmd", "/c", "\"mvn -version\""}

works for me, but launching a subshell is a bad practice so I am keeping this workaround as a last resort.对我有用,但启动子shell是一种不好的做法,所以我将此解决方法作为最后的手段。

Note that you are implicity running a sub-shell as the Windows command CMD.EXE is called to interpret the contents of mvn.cmd , so your value of cmd is equivalent to:请注意,当调用 Windows 命令CMD.EXE来解释mvn.cmd的内容时,您隐含地运行子外壳,因此您的cmd值等效于:

cmd = new String[]{ "cmd", "/c", "call mvn.cmd -version"};

If you get no error code from waitFor or no output or no exception, then the issue will be reported in the STDERR stream.如果没有从waitFor得到错误代码,或者没有输出或没有异常,那么问题将在 STDERR 流中报告。 Change to use ProcessBuilder instead and you can merge STDERR to STDOUT as follows:改为使用 ProcessBuilder,您可以将 STDERR 合并到 STDOUT,如下所示:

ProcessBuilder pb = new ProcessBuilder(cmd);
// No STDERR => merge to STDOUT
pb.redirectErrorStream(true);

Process p = pb.start();

Also, no need to write much code to consume STDOUT:此外,无需编写大量代码来使用 STDOUT:

try(var stdo = p.getInputStream()) {
    stdo.transferTo(System.out);
}

int rc = p.waitFor();
if (rc != 0) throw new RuntimeException("test failed");

Hopefully this will explain your problem with the mvn command.希望这能解释您的 mvn 命令问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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