1

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
lamcpp
  • 69
  • 9
  • `static final` is for indicating a _constant_ value. But your requirement is to have it _dynamic_. This isn't possible with constants. – Seelenvirtuose Dec 02 '22 at 11:22
  • Why do you need those different property files ? Apart from that you can't define the loading of a property file via environment variable... – khmarbaise Dec 02 '22 at 14:55

1 Answers1

1

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...

Dmitry Khamitov
  • 3,061
  • 13
  • 21