A properties file helps keep settings like URLs and usernames outside your test code. This makes tests easier to update and reuse.
0
0
Properties file for configuration in Selenium Java
Introduction
When you want to change the website URL without changing the test code.
When you need to store login credentials safely and separately.
When running tests on different environments like dev, test, and production.
When multiple testers share the same test scripts but need different settings.
When you want to avoid hardcoding values inside your Selenium tests.
Syntax
Selenium Java
Properties prop = new Properties(); FileInputStream fis = new FileInputStream("config.properties"); prop.load(fis); String url = prop.getProperty("url"); fis.close();
The properties file is a simple text file with key=value pairs.
Use getProperty to read values by their keys.
Examples
This is how the properties file looks. Each line has a key and a value separated by '='.
Selenium Java
# config.properties
url=https://example.com
username=testuser
password=pass123This Java code loads the properties file and prints the username value.
Selenium Java
Properties prop = new Properties(); try (FileInputStream fis = new FileInputStream("config.properties")) { prop.load(fis); String username = prop.getProperty("username"); System.out.println(username); }
Sample Program
This program reads the config.properties file and prints the stored URL, username, and password.
Selenium Java
import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class ConfigTest { public static void main(String[] args) { Properties prop = new Properties(); try (FileInputStream fis = new FileInputStream("config.properties")) { prop.load(fis); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); System.out.println("URL: " + url); System.out.println("Username: " + username); System.out.println("Password: " + password); } catch (IOException e) { System.out.println("Failed to load properties file."); } } }
OutputSuccess
Important Notes
Always close the FileInputStream to avoid resource leaks. Using try-with-resources is best.
Keep sensitive data like passwords secure and avoid committing them to public repositories.
Use meaningful keys in the properties file for easy understanding.
Summary
Properties files store configuration outside test code.
Use Java's Properties class to load and read these files.
This approach makes tests flexible and easier to maintain.