DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Solid Testing Strategies for Salesforce Releases
  • Apex Testing: Tips for Writing Robust Salesforce Test Methods
  • A General Overview of TCPCopy Architecture
  • Modes and Modality in Performance Testing

Trending

  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  • Integration Isn’t a Task — It’s an Architectural Discipline
  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Data Parameterization Using JSON With Selenium

Data Parameterization Using JSON With Selenium

After working with data parameterization in Excel, it's time to see how to do the same using Selenium.

By 
Remi Andonissamy user avatar
Remi Andonissamy
·
Jun. 06, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
73.8K Views

Join the DZone community and get the full member experience.

Join For Free

In my previous article, I explained how to do data parameterization using Excel files with the help of the Apache POI API. In this article, we will see how to achieve the same using JavaScript Object Notation (JSON) format files. 

Introduction

In testing, it is always important to test application features with different sets of data. Testing with one set of data that we use during recording or while creating a base script will not confirm the functionality of the application alone. For example: When we are doing a login test, it is extremely important to test with all possible valid and invalid credentials to ensure login functionality is working as expected.

One way to achieve testing multiple sets of data is to create individual test scripts/test cases that hold one set of hardcoded data. In this case, if we plan to test a functionality with ten different sets of data, we must create ten independent test scripts with different data. Another way is to create a base script with one set of data and manually change the data and execute the script 10 times.

Both approaches are time-consuming and practically difficult as well as impractical. The best and suggested approach to handling multiple sets of data is to have all the identified test data in any of the data sources like Excel, XML or in JSON files.

Here in this article, we will see how to achieve data parameterization with the help of JSON files.

Case Study

Mary is a newly-joined automation test developer in your project. She has performed exploratory testing on a Tricentis Demowebshop application and 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?

Here's the application URL.

Expectations

Help Mary test the login screen with two 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":"john@abc.com",
      "password":"abcd@1234",
    }
  },
  {
    "users":{
      "username":"doe@abc.com",
      "password":"pwd@1234",
    }
  },
  {
    "users":{
      "username":"henry@abc.com",
      "password":"abcd@1234",
    }
  }
  ]  

There are two types of JSON formats, Simple JSON and JSON Arrays.

Simple JSON

Data are stored here in simple text format which can be accessed easily. The JSON variable we define is an object, which contains many properties using the key:value structure. Refer to this example below for a Simple JSON structure:

var mydetails = {
  "Name" : "Jack",
  "Age" : "30",
  "Gender" : "Male"
};


Array JSON

JSON also supports storing multiple sets of data in the form of an Array structure. This can be achieved by keeping multiple objects in square brackets within one JSON structure as below:

var empdetails = [{
  "Name" : "John",
  "Designation" : "Project Manager",
  "Gender" : "Male"
},
{
  "Name" : "Doe",
  "Designation" : "Team Lead",
  "Gender" : "Male"
}];


Using an array index of the object empdetails, we can access all elements in the JSON array.

How To Work With JSON in Selenium

There are two ways using which we can load the JSON jar libraries in Eclipse:

1. Download/Add "json-simple-1.1.jar" to Java project

2. Use this Maven dependency in pom.xml file of a Maven project

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


How to Read Data From JSON file

Create a JSONParserinstance to parse the JSON file into a tree structure with any FileInputStream  object as the parameter

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


 JSONArray is used to parse JSON, which starts with Array brackets

JSONArray usersList = (JSONArray) obj;
System.out.println("Users List-> "+usersList); //This prints the entire json file


The .get method is used to access the values in the JSON by index

for(int i=0;i<usersList.size();i++) 
{
JSONObject users = (JSONObject) usersList.get(i);
System.out.println("Users -> "+users);//This prints every block - one json object
JSONObject user = (JSONObject) users.get("users");
System.out.println("User -> "+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);
}

How to Write Data to A JSON File

The "put" method is used to write data to a JSON file. 

user.put("result", result);


We can use a FileWriterobject and the toJSONString() method to write in a JSON file as a string.

file.append(usersList.toJSONString());


Selenium Example 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, IOException, ParseException {
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("Users List-> "+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 -> "+users);//This prints every block - one json object
            JSONObject user = (JSONObject) users.get("users");
            System.out.println("User -> "+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();
}
}
}


The output JSON file (Testdata1.json) will look like:

[
  {
    "users":{
      "result":"valid user",
      "username":"john@abc.com",
      "password":"abcd@1234",
    }
  },
  {
    "users":{
      "result":"invalid user",
      "username":"doe@abc.com",
      "password":"pwd@1234",
    }
  },
  {
    "users":{
      "result":"valid user",
      "username":"henry@abc.com",
      "password":"abcd@1234",
    }
  }
  ]


Conclusion

In this article, we have seen how to access JSON files in Selenium. The example we discussed will run for 3 iterations, validating the inputs and writing "valid" or "invalid" user in the "Result" column of the output JSON file.


file IO Test data

Opinions expressed by DZone contributors are their own.

Related

  • Solid Testing Strategies for Salesforce Releases
  • Apex Testing: Tips for Writing Robust Salesforce Test Methods
  • A General Overview of TCPCopy Architecture
  • Modes and Modality in Performance Testing

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!