Property files are simple text files used to store configuration data in key-value pairs. In Selenium, property files are commonly used to manage environment settings like URLs, login credentials, and other reusable data that may change based on the environment.
In most cases, no external dependencies are needed to work with property files in Selenium, as Java has built-in support through the `java.util.Properties` class.
You can create a property file (e.g., `config.properties`) to store configurations like URLs, usernames, passwords, and more. Below is an example of a property file and how to read from it in Selenium.
# Application URL
url=https://shariqsp.com/login
# User credentials
username=user1
password=password123
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertyFileReader {
public static Properties loadProperties(String filePath) {
Properties properties = new Properties();
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
properties.load(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
}
The `loadProperties()` method reads the property file and returns a `Properties` object containing the key-value pairs.
Here is an example that uses the `config.properties` file to automate a login test in Selenium.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Properties;
public class LoginWithPropertyFile {
public static void main(String[] args) {
// Load properties from the file
Properties properties = PropertyFileReader.loadProperties("./config.properties");
// Get values from the property file
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
// Setup WebDriver
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(url);
// Locate and input login credentials
WebElement userField = driver.findElement(By.id("username"));
WebElement passField = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("loginButton"));
userField.sendKeys(username);
passField.sendKeys(password);
loginButton.click();
driver.quit();
}
}
This example loads the application URL, username, and password from the property file and automates the login process using Selenium.