How to Read Data From Properties File in Selenium?
Why Properties File?
While automating a web application many user operations have to be performed and much input data is required to perform the testing. Sometimes the hardcoding of more input data can cause the code to not be reusable and consume more time to change the input in all the fields in the program, so the properties file is recommended to store the input data and give only the reference of the variable to the program. So changing the input data for testing in the properties file is only enough.
What is Properties File?
A property file is a file that is provided by Java, it is used to maintain the input data in the programming. The data present in the properties file is stored as Key-Value pairs, so we can access any data in this file by using the key.
Note: To Get started with Selenium please refer to the article How to Create a Selenium Maven Project with Eclipse to Open Chrome Browser?
Let’s Try to Automate the Scenario
- Opening the browser
- Entering the URL by getting the input from the properties file.
After completing the Maven project setup, Create a properties file in the same package such as (TestData.properties).
To create the properties file, right-click on the package and select >New>others file, then select General and select file.
Then click next, and type the file name with properties type.
Now we store the properties file with the data searchTeam=https://www.geeksforgeeks.org/
To use the properties file we have to import the dependency “import java.util.Properties;” and invoke the properties class
Properties props=new Properties();
To read the file we have to use the Java Filereader and set the path of the properties file.
FileReader reader=new FileReader("file path");
Then we have to load the File into the properties using the load method.
After that, we can access the data in the properties file by using the getProperty method
Now Write the Code for Automation
This code invokes the chrome driver and maximizes the window, after that it opens the Geeksforgeeks home page by reading the URL from the properties file.