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.
Join the DZone community and get the full member experience.
Join For FreeIn 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?
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 JSONParser
instance 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 FileWriter
object 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.
Opinions expressed by DZone contributors are their own.
Comments