Read data from Property File in Selenium Script using JAVA
In Selenium based JAVA project, .Properties files are used mainly to store configuration data like application URLs, database credentials etc. and web element locators.
.Properties file stores the data in a form of key & value pair as shown below:
Sample Project Structure:
Let’s try to understand it by using below scenario:
1. Open URL : google.com
2. Read the search text box locator from property file and type ‘selenium’.
3. Close browser.
Code:
import java.io.File; import java.io.FileInputStream; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class SampleTests { @Test public void test_propRead() throws Exception { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/driver/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://google.com"); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); Properties propertyReader = getPropertyFile("homePage.properties"); String textBoxLocator = propertyReader.getProperty("searchTextbox"); driver.findElement(By.xpath(textBoxLocator)).sendKeys("selenium"); Thread.sleep(2000); driver.quit(); } public Properties getPropertyFile(String fileName) throws Exception { File file = new File(System.getProperty("user.dir") + "/src/com/selenium/config/" + fileName); FileInputStream fileInputObj = new FileInputStream(file); Properties propObj = new Properties(); propObj.load(fileInputObj); return propObj; } }
If you see in above program, getPropertyFile() method is called to initialize the homePage.properties file and .properties file name is being passed as a parameter and this method will return the Properties class object.
Once initialization is done, then getProperty() method of Properties class is being called to get the value of any key stored in that Property file. It is that simple.
If you really like the information provided above, please don’t forget to hit a like on Facebook Page, you can also leave a comment.