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

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

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

gradle test -Darg1=something

这是我的测试:

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

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

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

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

参见-D的gradle command line documentation

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

    test {
       systemProperty "propertyName", "propertyValue"
    }

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

    test {
        systemProperties(System.getProperties())
    }

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

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

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

和运行也是一样。