java 如何使用 gradle test 将命令行参数传递给测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42492742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:41:16  来源:igfitidea点击:

How to pass command line arguments to tests with gradle test?

javagradlejunitargumentsjunit4

提问by Oleksandr

I am using gradle to run JUnit tests. The problem is that I need to pass arguments from the command line to tests. I tries to pass System properties but failed.

我正在使用 gradle 运行 JUnit 测试。问题是我需要将参数从命令行传递给测试。我尝试传递系统属性但失败了。

gradle test -Darg1=something

Here is my test:

这是我的测试:

public class MyTest {
    @Test
    public void someTest() throws Exception {
        assertEquals(System.getProperty("arg1"), "something");
    }
}

It fails because there is no arg1argument. Is it possible somehow to pass command line arguments?

它失败了,因为没有arg1争论。是否有可能以某种方式传递命令行参数?

回答by AdamSkywalker

When you run gradle test -Darg1=smth, you pass system parameter arg1to the Gradle JVM, not the test JVM where tests are run. It is designed this way to protect tests from side effects.

运行时gradle test -Darg1=smth,您将系统参数传递arg1给 Gradle JVM,而不是运行测试的测试 JVM。它的设计方式是为了保护测试免受副作用的影响。

If you need to propagate parameters to tests, use something like this

如果您需要将参数传播到测试,请使用类似这样的方法

test {
    systemProperty 'arg1', System.getProperty('arg1')
}

and run it the same way.

并以同样的方式运行它。

回答by ninnemannk

Use -D to send your parameters in. Like so:

使用 -D 发送您的参数。像这样:

./gradlew test -Dgrails.env=dev -D<yourVarName>=<yourValue>

See the gradle command line documentationof -D.

请参阅-D的gradle 命令行文档

To access it in the tests, you need to propagate it in your build.gradle file.

要在测试中访问它,您需要在 build.gradle 文件中传播它。

    test {
       systemProperty "propertyName", "propertyValue"
    }

You can also pass all System Properties like so:

您还可以像这样传递所有系统属性:

    test {
        systemProperties(System.getProperties())
    }