Does JUnit support properties files for tests?

Viewed 67359

I have JUnit tests that need to run in various different staging environments. Each of the environments have different login credentials or other aspects that are specific to that environment. My plan is to pass an environment variable into the VM to indicate which environment to use. Then use that var to read from a properties file.

Does JUnit have any build in capabilities to read a .properties file?

5 Answers

This answer is intended to help those who use Maven.

I also prefer to use the local classloader and close my resources.

  1. Create your test properties file, called /project/src/test/resources/your.properties

  2. If you use an IDE, you may need to mark /src/test/resources as a "Test Resources root"

  3. add some code:


// inside a YourTestClass test method

try (InputStream is = loadFile("your.properties")) {
    p.load(new InputStreamReader(is));
}

// a helper method; you can put this in a utility class if you use it often

// utility to expose file resource
private static InputStream loadFile(String path) {
    return YourTestClass.class.getClassLoader().getResourceAsStream(path);
}

If the aim is to load a .properties file into System Properties, then System Stubs (https://github.com/webcompere/system-stubs) can help:

The SystemProperties object, which can be used either as a JUnit 4 rule to apply it within a test method, or as part of the JUnit 5 plugin, allows setting properties from a properties file:

SystemProperties props = new SystemProperties()
    .set(fromFile("src/test/resources/test.properties"));

The SystemProperties object then needs to be made active. This is achieved either by marking it with @SystemStub in JUnit 5, or by using its SystemPropertiesRule subclass in JUnit4, or by executing the test code inside the SystemProperties execute method.

Related