pass a java parameter from maven

前端 未结 3 1610
醉梦人生
醉梦人生 2020-12-06 02:53

I need to execute some tests with maven, and pass a parameter from the command line.

My java code should get the parameter as: System.getenv(\"my_parameter1\");

相关标签:
3条回答
  • 2020-12-06 03:17

    The maven surefire plugin also has an option to set environment variables, just add this to your plugin configuration.

    <environmentVariables>
        <my_parameter1>value</my_parameter1>
    </environmentVariables>
    

    I think this requires that the plugin operates in fork mode, which is the default.

    0 讨论(0)
  • 2020-12-06 03:31

    Use

    ${env.my_parameter} 
    

    to access the environment variable in the pom.xml.

    You can use the help plugin to see which variables are set with

    mvn help:system
    

    However the normal properties usage should work too. In the large context however I am wondering... what do you want to do? There might be a simpler solution.

    0 讨论(0)
  • 2020-12-06 03:38

    System.getenv() reads environment variables, such as PATH. What you want is to read a system property instead. The -D[system property name]=[value] is for system properties, not environment variables.

    You have two options:

    1. If you want to use environment variables, use the OS-specific method of setting the environment variable my_parameter1 before you launch Maven. In Windows, use set my_parameter1=<value>, in 'nix use export my_parameter1=<value>.

    2. You can use System.getProperty() to read the system property value from within your code.

    example:

    String param = System.getProperty("my_parameter1");
    

    In you surefire plugin configuration, you can use:

    <configuration>
        <systemPropertyVariables>
            <my_property1>${my_property1}</my_property1>
        </systemPropertyVariables>
    </configuration>
    

    Which takes the Maven property _my_property1_ and sets it also in your tests.

    More details about this here.

    I'm not sure if system properties from Maven are automatically passed to tests and/or whether fork mode affects whether this happens, so it's probably a good idea to pass them in explicitly.

    0 讨论(0)
提交回复
热议问题