In this blog lets see how to take set of data from json file and pass that data to an application for login , how to read data from json file and write data into json file.
What is JSON simple dependency?
JSON. simple is a simple Java toolkit for JSON. You can use JSON. simple to encode or decode JSON text.
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
JSON - Syntax
Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a subset of JavaScript syntax; it includes the following −
Data is represented in name/value pairs.
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).
Square brackets hold arrays and values are separated by ,(comma).
Array
It is an ordered collection of values.
These are enclosed in square brackets which means that array begins with .[. and ends with .]..
The values are separated by , (comma).
Array indexing can be started at 0 or 1.
Arrays should be used when the key names are sequential integers.
Json file testdata.json
which has set of username and password to be used for Data driven
{
"userlogins": [
{
"username": "abc@gmail.com",
"password": "Test@123"
},
{
"username": "xyz@gmail.com",
"password": "Test@12"
},
{
"username": "adtest@yourstore.com",
"password": "adn"
}
]
}
Order of execution
This is a set of keywords or instruction to be executed after the start of test suite or test case execution. We will work on a project setup, where will use both setup and teardown. The opening and closing of browser are the common steps in test cases.
setup()
The setup() function is called once when the program starts. It's used to define initial environment properties such as opening browser, screen size and background color and to load media such as images and fonts as the program starts.
tearDown()
A teardown test case will execute at the end of your test run within a test folder. The tearDown() class method is called exactly once for a test case, after its final test method completes.Teardown test cases are used to perform post test execution actions. For example, a teardown test case can be used to close the browser, delete test data generated during test execution.
@BeforeClass
will be run before the entire test suits, runs once before the entire test fixture.
@BeforeClass will be executed only once.
@Before
will be run is executed before each test.
If your test class has ten tests, @Before code will be executed ten times
@AfterClass
will be called once per test class based,
the function with @AfterClass will be execute only one time after all the test functions in the class.
@After
the method annotated with @After will be called once per test based.
@After annotation will be executed after each of test function in the class having @Test annotation
@Test(dataProvider="dp")
TestNG Annotation is a piece of code which is inserted inside a program or business logic used to control the flow of execution of test methods.
@DataProvider(name="dp")
@DataProvider annotation helps us write data-driven test cases. The @DataProvider annotation enables us to run a test method multiple times by passing different data-sets. The name of this data provider. If it's not supplied, the name of this data provider will automatically be set to the name of the method.
JSON Parser
Interface JsonParser. Provides forward, read-only access to JSON data in a streaming way. This is the most efficient way for reading JSON data. The class Json contains methods to create parsers from input sources ( InputStream and Reader ).
JSON Array
A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having get and opt methods for accessing the values by index, and put methods for adding or replacing values.
JSON Object
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
File Reader
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. It is character-oriented class which is used for file handling in java.
File Writer
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java. Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.
Data Driven using Json file
Code to get username and password from json file and pass that value to login page
package jsonproject;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.AssertJUnit;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.time.Duration;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DDTestUsingJson
{ String[][] data=null;
WebDriver driver;
@BeforeClass
void setup()
{
WebDriverManager.chromedriver().setup();
WebDriverManager.chromedriver().clearDriverCache();
WebDriverManager.chromedriver().clearResolutionCache(); //WebDriverManager.chromedriver().browserVersion("110.0.0").setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
chromeOptions.setAcceptInsecureCerts(true);
chromeOptions.setScriptTimeout(Duration.ofSeconds(30));
chromeOptions.setPageLoadTimeout(Duration.ofMillis(30000));
chromeOptions.setImplicitWaitTimeout(Duration.ofSeconds(20));
chromeOptions.addArguments("--remote-allow-origins=*");
driver =new ChromeDriver(chromeOptions);
}
@AfterClass
void tearDown()
{
driver.close();
}
@Test(dataProvider="dp")
void login(String data)
{
String users[]=data.split(",");
driver.get("https://admin-demo.nopcommerce.com/");
driver.findElement(By.id("Email")).clear();
driver.findElement(By.id("Email")).sendKeys(users[0]);
driver.findElement(By.id("Password")).clear();
driver.findElement(By.id("Password")).sendKeys(users[1]);
driver.findElement(By.xpath("//button[normalize-space()='Log in']")).click();
String act_title=driver.getTitle();
String exp_title="Your store. Login";
AssertJUnit.assertEquals(act_title,exp_title);
}
@DataProvider(name="dp")
String[] readJson() throws IOException, ParseException
{
JSONParser jsonparser=new JSONParser();
FileReader reader=new FileReader(".\\jsonfiles\\testdata.json");
Object obj=jsonparser.parse(reader);
JSONObject userloginsJsonobj=(JSONObject)obj;
JSONArray userloginsArray=(JSONArray)userloginsJsonobj.get("userlogins");
String arr[]=new String[userloginsArray.size()];
for (int i=0; i<userloginsArray.size();i++)
{
JSONObject users=(JSONObject) userloginsArray.get(i);
String user=(String)users.get("username");
String pwd=(String)users.get("password");
arr[i]=user+"," +pwd ;
}
return arr;
}
}
Console output
##############################################
Reading data from json file
JSON file employee.json
{
"firstName": "Reka",
"lastName": "NV",
"address": [
{
"street": "Ohio",
"city": "plano",
"state": "Texas"
},
{
"street": "Puthur",
"city": "Pondy",
"state": "Pondy"
}
]
}
Code to read data from json file
package jsonproject;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadDataFromJsonFile {
public static void main(String[] args) throws IOException, ParseException
{
// TODO Auto-generated method stub
FileReader reader=new FileReader(".\\jsonfiles\\employee.json");
JSONParser jsonparser=new JSONParser();
Object obj=jsonparser.parse(reader);
JSONObject empjsonobj=(JSONObject)obj;
String fname=(String)empjsonobj.get("firstName");
String lname=(String)empjsonobj.get("lastName");
System.out.println("First name:" + fname);
System.out.println("Last name:" + lname);
JSONArray array=(JSONArray)empjsonobj.get("address");
for (int i=0; i<array.size();i++)
{
JSONObject address=(JSONObject) array.get(i);
String street=(String)address.get("street");
String city=(String)address.get("city");
String state=(String)address.get("state");
System.out.println("Adress of " +i+" is...");
System.out.println("Street :" + street);
System.out.println("Street :" + city);
System.out.println("Street :" + state);
}
}
}
Console output
##############################################
Writing data into json file
JSON file reka.json
JSON file is empty
Code to write into json file
package jsonproject;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JSONWriting {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
JSONObject jsonobject=new JSONObject();
jsonobject.put("Name","Raja");
jsonobject.put("age", 40);
JSONArray array= new JSONArray();
array.add("selenium");
array.add("magical java");
jsonobject.put("special qualities", array);
//FileWriter filewriter= new FileWriter("reka.json");
FileWriter filewriter= new FileWriter(".\\jsonfiles\\reka.json");
filewriter.write(jsonobject.toJSONString());
filewriter.close();
}
}
JSON file reka.json
{"special qualities":["selenium","magical java"],"age":40,"Name":"Raja"}
Conclusion:
I hope, This article will help you to understand How to do Data Driven testing using JSON File and how to read data from json file and write data into json file.
You must have got an idea on the topics explained in this blog. Lets explore more and learn New Topics.
Happy Learning
😀