Read Configurations from a Property File in Selenium

Hi all, in this article I will explain to you how to read configurations from a property file which holds global configurations and variables. You can add a utility class to handle this operation. You can name is PropertyReader, ConfigReader, PropertyManager, PropertyReader, etc. Let’s go on to learn how to do this.

First, I want to show you my project structure, it is a project which is written based on Page Object Model and in utilities package, I added a PropertyManager class to read configurations.properties file, get the global variables and configurations. I hold the configurations and variables in configurations.properties file.

configuration.properties File:

url = http://www.n11.com/
wrongUsername = [email protected]
wrongPassword = 11122233444

Property Manager Class:

Here, I used singleton design pattern to create the PropertyManager class only one time. In this way, we read and load the configuration data only one time. After the first call, we get the PropertyManager instance/object via getInstance() method.

loadData() method reads the configuration.properties file and assign the variables to the private variables. Lastly, we have getter methods to reach the variables such as getURL(), getWrongPassword(), getWrongUsername().

package utilities;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

//**********************************************************************************************************
//Author: Onur Baskirt
//Description: PropertyManager class reads global configurations and use them during test execution.
//**********************************************************************************************************
public class PropertyManager {

    private static PropertyManager instance;
    private static final Object lock = new Object();
    private static String propertyFilePath = System.getProperty("user.dir")+
            "\\src\\test\\resources\\configuration.properties";
    private static String url;
    private static String wrongUsername;
    private static String wrongPassword;

    //Create a Singleton instance. We need only one instance of Property Manager.
    public static PropertyManager getInstance () {
        if (instance == null) {
            synchronized (lock) {
                instance = new PropertyManager();
                instance.loadData();
            }
        }
        return instance;
    }

    //Get all configuration data and assign to related fields.
    private void loadData() {
        //Declare a properties object
        Properties prop = new Properties();

        //Read configuration.properties file
        try {
            prop.load(new FileInputStream(propertyFilePath));
            //prop.load(this.getClass().getClassLoader().getResourceAsStream("configuration.properties"));
        } catch (IOException e) {
            System.out.println("Configuration properties file cannot be found");
        }

        //Get properties from configuration.properties
        url = prop.getProperty("url");
        wrongUsername = prop.getProperty("wrongUsername");
        wrongPassword = prop.getProperty("wrongPassword");
    }

    public String getURL () {
      return url;
    }

    public String getWrongUsername () {
        return wrongUsername;
    }

    public String getWrongPassword () {
        return wrongPassword;
    }
}

Now, we can use PropertyManager class in our test or page classes. I will show how its usage below:

In HomePage Class, we got the URL value from configurations.properties file by using below line:

String baseURL = PropertyManager.getInstance().getURL();

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import utilities.PropertyManager;

public class HomePage extends BasePage {

    //*********Constructor*********
    public HomePage (WebDriver driver, WebDriverWait wait) {
        super(driver, wait);
    }

    //*********Page Variables*********
    String baseURL = PropertyManager.getInstance().getURL();

    //*********Web Elements*********
    String signInButtonClass = "btnSignIn";


    //*********Page Methods*********

    //Go to Homepage
    public void goToN11 (){
        driver.get(baseURL);
        //driver.navigate().to(baseURL)
    }

    //Go to LoginPage
    public void goToLoginPage (){
        click(By.className(signInButtonClass));
    }
}

Also, you can use PropertyManager in test classes as shown below:

String wrongUsername = PropertyManager.getInstance().getWrongUsername();

String wrongPassword = PropertyManager.getInstance().getWrongPassword();

package tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pages.HomePage;
import pages.LoginPage;

import utilities.PropertyManager;


public class LoginTests extends BaseTest {

    //Test Data
    String wrongUsername = PropertyManager.getInstance().getWrongUsername();
    String wrongPassword = PropertyManager.getInstance().getWrongPassword();

    private HomePage homePage;
    private LoginPage loginPage;

    @BeforeMethod
    public void methodLevelSetup() {
        //*************PAGE INSTANTIATIONS*************
        homePage = new HomePage(driver,wait);
        loginPage = new LoginPage(driver,wait);

        //*************PAGE METHODS********************
        //Open N11 HomePage
        homePage.goToN11();

        //Go to LoginPage
        homePage.goToLoginPage();
    }


    @Test (priority = 1, description="Invalid Login Scenario with wrong username and password.")
    public void invalidLoginTest_InvalidUserNameInvalidPassword ()  {
        //Login to N11
        loginPage.loginToN11(wrongUsername, wrongPassword);

        //*************ASSERTIONS***********************
        loginPage.verifyLoginPassword(("E-posta adresiniz veya şifreniz hatalı"));
    }

    @Test (priority = 2, description="Invalid Login Scenario with empty username and password.")
    public void invalidLoginTest_EmptyUserEmptyPassword ()  {
        //Login to N11
        loginPage.loginToN11("","");

        //*************ASSERTIONS***********************
        loginPage.verifyLoginUserName("Lütfen e-posta adresinizi girin.");
        loginPage.verifyLoginPassword("Bu alanın doldurulması zorunludur.");
    }
}

Here is the project code: https://github.com/swtestacademy/configreaderexample

Update:

There’s another library that you can use for read and write from a property file. In case you ever tried writing or updating a value in property file, all other properties are deleted in case you use java.util.Properties. There’s no way of updating a value without deleting the other entries.

In order to be able to achieve that challenge, you need to use a 3rd party library provided by Apache foundation. There might be other ones, but this is the one that we use in our projects right now.

compile group: 'org.apache.commons', name: 'commons-configuration2', version: '2.3'

After adding this dependency, logic is very simple. you need to create a FileBasedConfigurationBuilder object that’s bind to a properties file. Then you can read value by using getString(), getInt(),..  functions. There are many functions for different type of objects. But setting a value is much more straight forward. You just need to use setProperty as there are no different object types in properties file.

At the end of the operation, you just need to save the file by builder object.

Here’s a sample code.

  Parameters params = new Parameters();
        FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
                new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
                        .configure(params.properties()
                                .setFileName("application.properties"));
        Configuration conf = null;
        try {
            conf = builder.getConfiguration();
        } catch (ConfigurationException cex) {
            // loading of the configuration file failed
        }
        String username = conf.getString("username");
        System.out.println(username);

        conf.setProperty("username","swtestacademy");
        try {
            builder.save();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }

 

[fusion_widget_area name=”avada-custom-sidebar-seleniumwidget” title_size=”” title_color=”” background_color=”” padding_top=”” padding_right=”” padding_bottom=”” padding_left=”” hide_on_mobile=”small-visibility,medium-visibility,large-visibility” class=”” id=””][/fusion_widget_area]

Thanks.
Onur Baskirt

3 thoughts on “Read Configurations from a Property File in Selenium”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.