Follow below steps to read config file with selenium and Java
- Create a file named
config.propertiesin your project
url=https://example.com
browser=chrome
username=testuser
password=secret123
2. Read the properties file in Java
You can create a utility class to read the configuration file easily.
FileReader.java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class FileReader{
private Properties properties;
public FileReader() {
String filePath = System.getProperty(“user.dir”) + “/config/config.properties”;
try (FileInputStream fis = new FileInputStream(filePath)) {
properties = new Properties();
properties.load(fis);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(“Failed to load config.properties file.”);
}
}
public String getProperty(String key) {
String value = properties.getProperty(key);
if (value == null) {
throw new RuntimeException(“Key not found in config file: ” + key);
}
return value;
}
}
3. Use the config values in your Selenium test
import org.testng.annotations.Test;
public class ExampleTest {
@Test
public void ReadFile() {
ConfigReader config = new ConfigReader();
String browser = config.getProperty(“browser”);
String url = config.getProperty(“url”);
}
}