Home > Back-end >  How to select indicated file from properties using maven
How to select indicated file from properties using maven

Time:12-08

I am using java in maven project for test automation. I have two properties files:

  • DEV.properties (environment: DEVELOPMENT)
  • PROD.properties (environment: PRODUCTION)

I read this properties:

private static final Properties properties;
private static final String CONFIG_PROPERTIES_FILE = "DEV.properties";

static {
    properties = new Properties();
    InputStream inputStream = Property.class.getClassLoader().getResourceAsStream(CONFIG_PROPERTIES_FILE);
    try {
        properties.load(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

In "CONFIG_PROPERTIES_FILE" variable I can indicate which environment I want to use (DEV or PROD). How to do the same with a terminal using maven? Something like:

 private static final String CONFIG_PROPERTIES_FILE = $environment;

and in terminal:

mvn clean test $environment=DEV.properties

or:

mvn clean test $environment=PROD.properties

CodePudding user response:

The following should work.

public class MyTest {
    private static final String CONFIG_PROPERTIES_FILE = System.getProperty("environment");

    static {
        var properties = new Properties();
        InputStream inputStream = MyTest.class.getResourceAsStream(CONFIG_PROPERTIES_FILE);
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Now, you have to run mvn like in the below example because my assumption is that you run Maven Surefire Plugin in a forked mode which is a default mode.

mvn clean test -DargLine="-Denvironment=DEV.properties"

By using the argLine you can specify system properties that you want to pass to a forked JVM. Without the argLine those -D properties will not be passed from the so-called main (mvn) JVM to a child (forked) one used by the Surefire to run the tests.

For a bit of background on that "argLine" machinery you can check out this answer (and many others) or the Maven mail thread. Both date back to 14 years ago...

  • Related