如何使用 gradle test 将命令行参数传递给测试?
我正在使用 gradle 运行 JUnit 测试.问题是我需要将参数从命令行传递给测试.我尝试传递系统属性但失败了.
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 test -Darg1=something
这是我的测试:
public class MyTest {
@Test
public void someTest() throws Exception {
assertEquals(System.getProperty("arg1"), "something");
}
}
失败是因为没有 arg1
参数.是否有可能以某种方式传递命令行参数?
It fails because there is no arg1
argument.
Is it possible somehow to pass command line arguments?
当你运行 gradle test -Darg1=smth
时,你将系统参数 arg1
传递给 Gradle JVM,而不是运行测试的测试 JVM.这样做是为了保护测试免受副作用的影响.
When you run gradle test -Darg1=smth
, you pass system parameter arg1
to the Gradle JVM, not the test JVM where tests are run. It is designed this way to protect tests from side effects.
如果您需要将参数传播到测试,请使用类似这样的方法
If you need to propagate parameters to tests, use something like this
test {
systemProperty 'arg1', System.getProperty('arg1')
}
并以同样的方式运行它.
and run it the same way.