Writing test data to the JSON file for Selenium WebDriver

Category: Parameterization, Selenium WebDriver 34 1

Yesterday we discussed JSON data parsing, which means reading test data from JSON. When we are using Excel sheet, we, seldom, write back data to the sheet. Similarly, today we are going to discuss the technique to be writing test data to the JSON file.

We already discussed that JSONObject acts like the Map, whereas, JSONArray acts like the ArrayList. Therefore, we will use these concepts as the base for writing test data to the JSON file.

Advantages of writing test data to the JSON file

  • The code is less complex
  • Ease to maintain the code
  • Convenience in maintaining the test data text file
  • Faster to write

Scenario

We have a scenario to maintain test data of the student in JSON file. So, the test data will include student’s first name, last name, age, address which contains the street name, house number, postal code, and in the different array it should contain phone numbers of personal and home.

Coding approach

How shall we proceed with the coding of the above scenario?

We will first create an instance of JSONObject which is actually the test data in JSON. As we all know JSONObject has the Map representation so we use put() method to store the test data in key-value pairs. Sometimes we use test data with a new curly brace in JSON to designate the separate entity, let’s say address and phone numbers here. Hence, we can first keep them either in LinkedHashMap or JSONArray and then we will put them in the JSONObject. In any way, we have to put them as JSONObject.

In the end, we just write the entire Map to file and we flush and close them.

Sample code for writing test data to the JSON file 

JSONWrite.json file Created

Below is the screenshot of new JSON file created after writing test data. We can even write the test data in any of the existing JSON file, but when you write directly then the existing data will be lost so you must make sure to carry forward the existing test data from the pre-existing json file. Loss of existing test data while writing to the pre-existing JSON file could be the disadvantage of this technique.

Project Hierarchy

 

 

Writing test data to the JSON file

Friends, Don’t miss the latest update on Automation Testing. Join our Facebook group and be the participant of the mindful knowledge sharing conversation. Click below to join.

Join Inviul fb group

Related Articles

One thought on “Writing test data to the JSON file for Selenium WebDriver

Add Comment