Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass command line arguments to tests with gradle test? [duplicate]

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

Here is my test:

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

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

like image 604
Oleksandr Avatar asked Feb 27 '17 18:02

Oleksandr


People also ask

Is it possible to pass command line arguments to a test?

It is possible to pass custom command line arguments to the test module.

How do you run a test case using Gradle command?

You can do gradle -Dtest. single=ClassUnderTestTest test if you want to test single class or use regexp like gradle -Dtest. single=ClassName*Test test you can find more examples of filtering classes for tests under this link.


2 Answers

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

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

See the gradle command line documentation of -D.

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

    test {
       systemProperty "propertyName", "propertyValue"
    }

You can also pass all System Properties like so:

    test {
        systemProperties(System.getProperties())
    }
like image 63
ninnemannk Avatar answered Oct 18 '22 20:10

ninnemannk


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.

like image 19
AdamSkywalker Avatar answered Oct 18 '22 22:10

AdamSkywalker