Does JUnit support properties files for tests?

java has built in capabilities to read a .properties file and JUnit has built in capabilities to run setup code before executing a test suite.

java reading properties:

Properties p = new Properties();
p.load(new FileReader(new File("config.properties")));

junit startup documentation

put those 2 together and you should have what you need.


//
// Load properties to control unit test behaviour.
// Add code in setUp() method or any @Before method (JUnit4).
//
// Corrected previous example: - Properties.load() takes an InputStream type.
//
import java.io.File;
import java.io.FileInputStream;        
import java.util.Properties;

Properties p = new Properties();
p.load(new FileInputStream( new File("unittest.properties")));

// loading properties in XML format        
Properties pXML = new Properties();
pXML.loadFromXML(new FileInputStream( new File("unittest.xml")));

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);
}

It is usually preferred to use class path relative files for unit test properties, so they can run without worrying about file paths. The path may be different on your dev box, or the build server, or where ever. This will also work from ant, maven, eclipse without changes.

private Properties props = new Properties();

InputStream is = ClassLoader.getSystemResourceAsStream("unittest.properties");
try {
  props.load(is);
}
catch (IOException e) {
 // Handle exception here
}

putting the "unittest.properties" file at the root of the classpath.

Tags:

Java

Junit