Use of .properties file in selenium project with TestNG
Tags: automation, selenium, testng, extentreports
Published: 2021-05-24 00:01:49

**.properties** files are mainly used in Java programs to maintain project configuration data, database config or project settings, etc. You can easily read properties from some file using an object of type Properties. This is a utility provided by Java itself.

In simple words Properties file is a file with **.properties** as extension. Each parameter in properties file is stored as a pair of strings, in key-value pair format(key = value), where each key is on one line. They can also be used for storing strings for Internationalization and localization.

Since **.properties** file is a java library from *.util* package we do not need any dependencies. but because I’m using TestNG, Selenium and doing browser action lets start with a maven project.

###1.Adding Dependencies to the pom.xml file

First create a maven project and name it as **PropertiesFile.** Then add following dependencies to the **pom.xml** file.

First copy the selenium dependency and set it in the pom.xml file.
```javascript
https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java/3.141.59
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>
``` 
Copy the TestNG dependency and set it in the pom.xml file.
```javascript
https://mvnrepository.com/artifact/org.testng/testng
<! —  https://mvnrepository.com/artifact/org.testng/testng →
<dependency>
 <groupId>org.testng</groupId>
 <artifactId>testng</artifactId>
 <version>7.4.0</version>
 <scope>test</scope>
</dependency>
``` 
As well as set the WebDriver maven dependency for make our test simple.
```javascript
https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager/4.4.3
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>4.4.3</version>
</dependency>
``` 
That all we have to do as prerequisites and you are good to go…

###2.Create a file with a .properties extension

Under **PropertiesFile** project create a package called *config.*
Right click on it and create a File as *config.properties.*
This is the vey first step we are going to do by initializing our key value pair as below.
```javascript
browser=chrome
``` 

###3.Create a Java class

Create a new class called **“PropertiesFile”.** And include the *main()* method.

For understand the behavior of the **.properties** file lets write a simple code.

I have written this code with the Code Modular and to handle the exceptions its written in the *try-catch* block.

```javascript
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class PropertiesFile {
//Create a object for class properties 
 static Properties prop = new Properties();
 //defining the project path
 static String projectPath = System.getProperty("user.dir");
public static void main(String[] args) {
getProperties();
  setProperties();
  getProperties();
}
public static void getProperties() {
try {
//create a object for class InputStream
   InputStream input = new FileInputStream(projectPath + "/src/test/java/test/config.properties");
   //Load properties file
   prop.load(input);
   //get values from properties file
   String browser = prop.getProperty("browser");
   System.out.println(browser);
} catch (Exception exp) {
System.out.println(exp.getMessage());
   System.out.println(exp.getCause());
   exp.printStackTrace();
}
}
public static void setProperties() {
try {
//create a object for class OuputStream
   OutputStream output = new FileOutputStream(projectPath + "/src/test/java/test/config.properties");
   //Load properties file and set firefox
   prop.setProperty("browser", "firefox");
   //store values i properties file
   prop.store(output, "setting firefox");
} catch (Exception exp) {
System.out.println(exp.getMessage());
   System.out.println(exp.getCause());
   exp.printStackTrace();
  }
}
}
``` 
Press *CTRL + SHIFT + O* to import all classes from the *.util* package.
This code will read the value from **.properties** file and print the value in the console. Then It will write new value to the same key from **.properties** file and again call the previous function. Lets understand what I have done here inside the code.

First I have created two methods inside the class named **getProperties()** and **setProperties()**
```javascript
getProperties()
setProperties()
``` 
**getProperties()** will read the values from the **.properties** file.
**setProperties()**will write values to the **.properties** file.

Then I have created a object called *prop* from the class level.
```javascript
static Properties prop = new Properties();
``` 
In **getProperties()** method I have set the path to the **.properties** file and created the object *input*
```javascript
InputStream input = new FileInputStream(projectPath + "/src/test/java/test/config.properties");
``` 
And In here its reading the value from the **.properties** file and store in the variable *browse**
```javascript
String browser = prop.getProperty("browser");
``` 
In **setProperties()** method I have again set the path to the **.properties** file and created the object *output*
```javascript
OutputStream output = new FileOutputStream(projectPath + "/src/test/java/test/config.properties");
``` 
Here its overwriting the value in the **.properties** file to the *firefox* and finally store it.
```javascript
prop.setProperty("browser", "firefox");
prop.store(output, "setting firefox");
``` 
And in the **.properties** file you will see its replaced with the value *firefox* and the date is also has been set.
```javascript
#setting firefox
#Mon May 24 01:08:49 IST 2021
browser=firefox
``` 
So this is how we write and read from the **.properties** file. So lets try to put another step by using TestNG and doing some browser actions with selenium.

###4.Create a TestNG Class

Use the same package and create another class called **"PropertiesFileTestNG".** And do not include a *main()* method since it is a TestNG class.

For this example I will use a code which I had in my previous article **"How to use Extent Reports with TestNG in Selenium Java"**

Just check in the link below. I have explained the code there.
https://manulwick.medium.com/how-to-use-extent-reports-with-testng-in-selenium-java-c892cf256737

This will go to the site *www.ebay.com* and then it will validate site by comparing Title. After will enter "mobile" in the search box and hit enter.
I have used **@Test** annotation to execute the test case which is *test1* and used *extent Reports* as the reporting library.

```javascript
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import io.github.bonigarcia.wdm.WebDriverManager;
public class PropertiesFileTestNG {
//creating driver object
 private static WebDriver driver = null;
//setting expected title from the ebay.com/Daraz.lk
 static String expectedTitleebay ="Electronics, Cars, Fashion, Collectibles & More | eBay";
 static String expectedTitledaraz ="Online Shopping Sri Lanka: Clothes, Electronics & Phones | Daraz.lk";
//create the htmlReporter object
ExtentSparkReporter htmlReporter;
 ExtentReports extent;
 ExtentTest test1;
 
 public static String browserName = null;
 
 @BeforeSuite
 public void setup() {
  
  PropertiesFile.getProperties();
if(browserName.equalsIgnoreCase("chrome")) {
   //initializing and starting the chrome browser
   WebDriverManager.chromedriver().setup();
   driver = new ChromeDriver();
    
  }else if(browserName.equalsIgnoreCase("firefox")) {
   //initializing and starting the firefox browser
   WebDriverManager.firefoxdriver().setup();
   driver = new FirefoxDriver();
   
  }
htmlReporter = new ExtentSparkReporter("extentReport.html");
  //create ExtentReports and attach reporter(s)
  extent = new ExtentReports();
  extent.attachReporter(htmlReporter);
 
 }
@Test  
 public void test1() throws InterruptedException {
   
  //creates a toggle for the given test, add all log events under it
  test1 = extent.createTest("ebay Search Test", "test to validate search box ");
test1.log(Status.INFO, "Starting test case");
  
  if (browserName.equals("firefox")) {
   System.out.println("Starting test on Firefox");
   test1.pass("Starting test on Firefox");
  }else if(browserName.equals("chrome")) {
   System.out.println("Starting test on chrome");
   test1.pass("Starting test on chrome");
  }
  
  //maximize the window 
  driver.manage().window().maximize();
  test1.pass("maximize has done");
//Navigate to Ebay.com
  driver.get("https://www.ebay.com");
  Thread.sleep(1000);
  test1.pass("Navigate to Ebay.com");
//compare whether the title id matching
  String actualTitle = driver.getTitle();
  Assert.assertEquals(actualTitle, expectedTitleebay);
  test1.pass("title is correct");
//enter in the TextBox
  driver.findElement(By.xpath("//*[@id=\"gh-ac\"]")).sendKeys("Mobile");
  test1.pass("Entered text in the text box");
  Thread.sleep(1000);
  //hit enter
  driver.findElement(By.xpath("//*[@id=\"gh-btn\"]")).sendKeys(Keys.RETURN); 
  test1.pass("Press keybopard enter key");
  Thread.sleep(1000);
 
 }
 
 @AfterSuite
 public void tearDown() {
driver.quit();
  test1.pass("closed the browser");
test1.info("test completed"); 
  
  //write results into the file
  extent.flush();
PropertiesFile.setProperties();
}
}
``` 
I have created a variable named *browserName* in this class so I can reference it with the **PropertiesFile** class.
```javascript
public static String browserName = null;
```

I have put this reference in the **PropertiesFile** so the browser can be defined from **.properties** file.
```javascript
PropertiesFileTestNG.browserName = browser;
``` 

Here the only thing we have to do is change the key value in the **.properties** file as firefox or chrome so the rest will continue with the classes **PropertiesFile** and **PropertiesFileTestNG**

Since we are using Extent Reports here as the reporting library Calling the **flush** method writes/updates the test information of your reporter to the destination type.

So lets have a look at it.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4r3j3ud41y9aog1zto1.PNG)
extentReport.html (firefox)


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpmbbnulp9lneptccoyt.PNG)
extentReport.html (chrome)


As you can see its clearly mentioning the status and all the tests are passing. And if you noticed that i have called the **PropertiesFile** again to write the status of our test to the **.properties** file.

```javascript
PropertiesFile.setProperties();
``` 

Before that make sure you replace **setPropertiesFile** with the following code line. This will write a new key *result* setting the value as *test passed*
```javascript
prop.setProperty("result", "test passed");
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m61twf0jsvjizj51lrt2.PNG)
config.properties

So its clear that if the **.properties** file is updating with this value our test has passed.
Ok that's it…

In this article i have shown you guys What is **.properties** file, How to create one with our selenium project as well as with a TestNG. Also we analyzed test results with the Reporting library Extent Reports and we also updated the **.properties** file after a successful automation.

In my next article let's talk about how to run this same selenium test framework using Jar files from command line without using any IDE.

For your reference find my GitHub project [here](https://github.com/mwickramanayaka/Daraz-Add-to-card-test-Selenium.git) 

####𝑻𝑯𝑰𝑵𝑲 𝑸𝑼𝑨𝑳𝑰𝑻𝒀!