Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Data-Driven Testing Using JavaScript Object Notation (JSON) and Selenium

DZone 's Guide to

Data-Driven Testing Using JavaScript Object Notation (JSON) and Selenium

Take a look at how you can use Selenium and JSON to verify login functionality using this tutorial.

· Performance Zone ·
Free Resource

Introduction

According to Guru 99, "Data-driven testing is a test automation framework which stores test data for applications in a table or spreadsheet format. This helps automation testers to have a single test script which can execute tests for all the test data in the Excel file." 

The input data for testing can be stored in single or multiple data sources like XLS, XLSX, XML or in JSON files. Here we will see how to manipulate data stored using JSON. 

Why Data-Driven Testing?

To ensure whether a particular functionality of the application is working correctly, we need to test with different sets of test data. For example, if we want to ensure the login functionality of an application is working correctly, we need to provide all valid credentials as well as invalid credentials, and test. This ensures that the application is working as expected for all valid and invalid sets of test data.  

There are various ways we can achieve data-driven testing:

  1. Create n number of unique scripts for each and every planned test data;

  2. After recording/writing the base script, change the test data one by one physically and execute for all sets;

  3. Have the test data in any data source like .xls or JSON files. Import/Load the data source in your test and fetch the data one at a time and execute the script.

From the given three ways, the first two are practically impossible and would take more time to design and execute the test cases. The third way is the ideal approach, which saves lots of time and helps us to do data-driven testing effectively and efficiently. In this article, we will see how to data drive using JSON files. In Selenium, we can handle JSON files by loading "json-simple" jar files or using Maven dependency.

Case Study

Mary is a newly joined automation test developer in your project. She has performed exploratory testing on a Tricentis Demowebshop application and is trying to login with multiple users on the application. The test data is provided in JSON format. Can you guide Mary to complete this activity?

Objective

Help Mary to test the login screen with tow sets of valid and one set of invalid credentials given in the JSON file. Report in the JSON file with “Valid user” or “Invalid user” based on the application functionality.

Input JSON File:

[
{
"users": {
"username": "remi.jullian@accenture.com",
"password": "test@1234",
}
},
{
"users": {
"username": "remi1@accenture.com",
"password": "test@1234",
}
},
{
"users": {
"username": "remi@accenture.com",
"password": "test@1234",
}
}
]


Output JSON File:

[
  {
    "users":{
      "result":"valid user",
      "password":"test@1234",
      "username":"remi.jullian@accenture.com"
    }
  },
  {
    "users":{
      "result":"invalid user",
      "password":"test@1234",
      "username":"remi1@accenture.com"
    }
  },
  {
    "users":{
      "result":"valid user",
      "password":"test@1234",
      "username":"remi@accenture.com"
    }
  }
]


Storing Simple JSON Data

  • JSON stands for JavaScript Object Notation.

  • It stores the data in a text format in an organized way which is easy to access.

  • We create an object that we can access using a variable “details” (Refer to the code snippet below).

  • The variable value is an object that contains multiple properties using a “name:value” pair.

Example JSON:

var details = {
  "Age" : "24",
  "Hometown" : "Chennai, India",
  "Gender" : "Male"
};


Storing JSON data in Arrays

  • We can also have multiple sets of data in JSON. To do this, we can store multiple objects in square brackets. We call this as a JSON Array.

Example JSON Array:

var empdetails = [{
  "Name" : "John",
  "Designation" : "Software Engineer",
  "Gender" : "Male"
 },
 {
  "Name" : "Peter",
  "Designation" : "Manager",
  "Gender" : "Male"
 }];



To access this information, we need to access the array index of the empdetails variable we wish to access.

How to Access JSON Files in Selenium-Java

  • Option 1: Download/Add "json-simple-1.1.jar" to the Java project

  • Option 2: Use the below Maven dependency in the pom.xml file of a Maven project

<dependency>
     <groupId>com.googlecode.json-simple</groupId>
     <artifactId>json-simple</artifactId>
     <version>1.1.1</version>
</dependency>


Read Data From JSON File

Create a JSONParser instance to parse JSON into a tree structure with any FileInputStream  object (using the path of the source file) as a parameter:

JSONParser jsonParser = new JSONParser();
FileReader reader = new FileReader("Testdata.json");
//Read JSON file
Object obj = jsonParser.parse(reader);


 JSONArrayis used to parse JSON which starts with Array brackets

JSONArray usersList = (JSONArray) obj;
System.out.println(usersList); //This prints the entire json file


The internal form is an object using the get method for accessing the values by index

for(int i=0;i<usersList.size();i++) 
{
JSONObject users = (JSONObject) usersList.get(i);
System.out.println(users);//This prints every block - one json object
JSONObject user = (JSONObject) users.get("users");
System.out.println(user); //This prints each data in the block
String username = (String) user.get("username");
String password = (String) user.get("password");
  System.out.println("The username in JSON is -> "+username);
  System.out.println("The password in JSON is -> "+password);
}

To Write Data From JSON File

We can use the putmethod to write data in JSON file.

user.put("result", result);
  • We can use a FileWriter object and  toJSONString()method to write in a JSON file as a string.

file.append(usersList.toJSONString());


Selenium Code to Handle JSON Files:

public class JSONHandling {
WebDriver driver;

@BeforeTest
public void beforeTest() throws IOException {
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE, "null");
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\Drivers\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get("http://demowebshop.tricentis.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}

@Test
public void testAut() throws InterruptedException {
readWriteJSON();
}

@AfterTest
public void afterTest() {
driver.close();
}

public String login(String username, String password) throws InterruptedException {
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.name("Email")).sendKeys(username);
driver.findElement(By.name("Password")).sendKeys(password);
driver.findElement(By.xpath("//input[@class='button-1 login-button' and @value='Log in']")).click();

if(driver.findElements(By.xpath("//input[@id='vote-poll-1']")).size()>0)
{
String uname = driver.findElement(By.xpath("//a[@href='/customer/info']")) .getText();
if(uname.equals(username))
driver.findElement(By.xpath("//a[@href='/logout']")).click();
}
else 
{
driver.findElement(By.xpath("//a[@href='/login']")).click();
return "Invalid User";
}
return "Valid User";
}

@SuppressWarnings("unchecked")
public void readWriteJSON() throws InterruptedException, IOException, ParseException {
JSONParser jsonParser = new JSONParser();
try  {
FileReader reader = new FileReader("Testdata.json");
//Read JSON file
            Object obj = jsonParser.parse(reader);
            JSONArray usersList = (JSONArray) obj;
            System.out.println(usersList); //This prints the entire json file
            for(int i=0;i<usersList.size();i++) {
            JSONObject users = (JSONObject) usersList.get(i);
            System.out.println(users);//This prints every block - one json object
            JSONObject user = (JSONObject) users.get("users");
            System.out.println(user); //This prints each data in the block
            String username = (String) user.get("username");
            String password = (String) user.get("password");
            String result = login(username,password);
            user.put("result", result);

            //Write JSON file
                try (FileWriter file = new FileWriter("Testdata1.json")) {
                    file.append(usersList.toJSONString());
                    file.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            System.out.println(user);
             }
         } catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}


Conclusion

This is how we can access JSON files in Selenium. The above test goes for three iterations, validating the inputs and writing "valid" or "invalid" user in the "Result" column in JSON file. 

Topics:
selenium ,data driven testing ,json ,login ,tutorial ,performance ,case study

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}