Properties file for configuration in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.FileInputStream; import java.io.IOException; import java.time.Duration; import java.util.Properties; public class LoginTest { private WebDriver driver; private WebDriverWait wait; private Properties config; @BeforeClass public void setUp() throws IOException { // Load properties file config = new Properties(); FileInputStream fis = new FileInputStream("config.properties"); config.load(fis); fis.close(); // Setup WebDriver driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } @Test public void testLoginWithProperties() { driver.get("http://example.com/login"); // Enter username WebElement usernameInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username"))); usernameInput.sendKeys(config.getProperty("username")); // Enter password WebElement passwordInput = driver.findElement(By.id("password")); passwordInput.sendKeys(config.getProperty("password")); // Click login button WebElement loginButton = driver.findElement(By.id("loginBtn")); loginButton.click(); // Wait for URL to change to dashboard wait.until(ExpectedConditions.urlToBe("http://example.com/dashboard")); // Assert URL String currentUrl = driver.getCurrentUrl(); Assert.assertEquals(currentUrl, "http://example.com/dashboard", "User should be redirected to dashboard after login"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test class uses Selenium WebDriver with TestNG to automate login using credentials from a properties file.
setUp(): Loads the config.properties file using Properties class and initializes the ChromeDriver and explicit wait.
testLoginWithProperties(): Opens the login page, waits for username input to be visible, enters username and password from the properties file, clicks login, waits until the URL changes to the dashboard URL, then asserts the URL is correct.
tearDown(): Closes the browser after the test finishes.
Explicit waits ensure elements are ready before interacting. Using properties file keeps credentials outside the code for easy updates.
Now add data-driven testing with 3 different username and password combinations from the properties file