NỘI DUNG BÀI HỌC

✳️ Đọc Data từ JSON file
✳️ Chỉnh sửa giá trị trong JSON file
✳️ Chỉnh sửa thuộc tính trong JSON file

✅ Đọc Data từ JSON file

Đầu tiên tạo các file JSON và chứa cấu trúc data json cho các test cases.

Login.json

{
   "username": "anhtester",
   "password": "Demo@123"
}

RegisterUser.json

{
   "username": "user2812A1",
   "firstName": "User",
   "lastName": "2812A1",
   "email": "user2812A1@email.com",
   "password": "Demo@123",
   "phone": "0123456789",
   "userStatus": 1
}


Tiếp theo bên phần test case chỉ cần trỏ đường dẫn của file json vào hàm body() của request là xong. Lưu ý nhớ thêm cấu trúc new File()

import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.Test;

import java.io.File;

import static io.restassured.RestAssured.given;

public class DemoReadJsonFile {
    @Test
    public void testLoginUser() {
        //Read Json file path
        String filePath = "src/test/resources/testdata/Login.json";

        RequestSpecification request = given();
        request.baseUri("https://api.anhtester.com/api")
                .accept("application/json")
                .contentType("application/json")
                .body(new File(filePath));

        Response response = request.when().post("/login");
        response.prettyPrint();
        response.then().statusCode(200);
    }

    @Test
    public void testRegisterUser() {
        //Read Json file path
        String filePath = "src/test/resources/testdata/RegisterUser.json";

        RequestSpecification request = given();
        request.baseUri("https://api.anhtester.com/api")
                .accept("application/json")
                .contentType("application/json")
                .body(new File(filePath));

        Response response = request.when().post("/register");
        response.prettyPrint();
        response.then().statusCode(200);
    }
}


Yeah phần này rất đơn giản, chỉ như vậy thôi 😁

 

✅ Chỉnh sửa giá trị trong JSON file

Thay vì các bạn chỉnh sửa giá trị trong file JSON thủ công bằng tay thì giờ mình sử dụng code luôn cho tiện trong quá trình thực thi test cases.

Và nhiều khi chúng ta cần thay đổi giá trị trên cùng 1 file json để phục vụ cho nhiều test cases khác nhau.

Chúng ta sẽ sử dụng thư viện GSON để giải quyết câu chuyện này khá dễ dàng.

TestJsonFile01.json

{
   "firstname": "Anh",
   "lastname": "Tester",
   "totalprice": 111,
   "depositpaid": true,
   "bookingdates": {
      "checkin": "2023-12-28",
      "checkout": "2024-03-15"
   },
   "additionalneeds": "Technology"
}

Giờ muốn thay đổi giá trị của field additionalneeds

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.testng.annotations.Test;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DemoEditJsonFile {
    @Test
    public void testUpdateValueInJson() {

        Reader reader;
        String filePath = "src/test/resources/testdata/TestJsonFile01.json";

        try {
            reader = Files.newBufferedReader(Paths.get(filePath));

            Gson gson = new Gson();
            //Convert Json file to Json Object
            JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
            System.out.println("Original JSON: " + jsonObject);

            //Update value if exist key
            jsonObject.addProperty("additionalneeds", "Update New Value");

            System.out.println("Modified JSON: " + jsonObject);

            //Store new Json data to new file
            File jsonFile = new File("src/test/resources/testdata/TestJsonFileEdited.json");
            OutputStream outputStream = new FileOutputStream(jsonFile);
            outputStream.write(gson.toJson(jsonObject).getBytes());
            outputStream.flush();

            //Close reader
            reader.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Kết quả:

Original JSON: {"firstname":"Anh","lastname":"Tester","totalprice":111,"depositpaid":true,"bookingdates":{"checkin":"2023-12-28","checkout":"2024-03-15"},"additionalneeds":"Technology"}
Modified JSON: {"firstname":"Anh","lastname":"Tester","totalprice":111,"depositpaid":true,"bookingdates":{"checkin":"2023-12-28","checkout":"2024-03-15"},"additionalneeds":"Update New Value"}

===============================================
Default Suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================


Giá trị của field additionalneeds đã được cập nhật mới thành công.

Kết quả ví dụ trên lưu vào file JSON mới. Bạn muốn lưu vào file JSON cũ thì gọi tên vào thôi.

Nếu JSON là dạng mảng object như sau:

TestJsonFile03.json

[
   {
      "firstname": "Anh",
      "lastname": "Tester",
      "totalprice": 111,
      "depositpaid": true,
      "bookingdates": {
         "checkin": "2023-12-28",
         "checkout": "2024-03-15"
      },
      "additionalneeds": "Technology"
   },
   {
      "firstname": "An",
      "lastname": "Vo",
      "totalprice": 222,
      "depositpaid": false,
      "bookingdates": {
         "checkin": "2023-12-30",
         "checkout": "2024-03-24"
      },
      "additionalneeds": "Technology"
   }
]

Thì chúng ta sẽ xử lý theo dạng mảng, cần xác định thứ tự object cần chỉnh sửa sau đó mới chỉnh sửa giá trị theo key sau.

Giả sử An chỉnh sửa field "lastname" của object đầu tiên, chúng ta làm như sau:

@Test
public void testUpdateValueInJson03_ArrayObject() {

    Reader reader;
    String filePath = "src/test/resources/testdata/TestJsonFile03.json";

    try {
        reader = Files.newBufferedReader(Paths.get(filePath));

        Gson gson = new Gson();
        //Convert Json file to JsonArray
        JsonArray jsonArray = gson.fromJson(reader, JsonArray.class);

        System.out.println("Original JSON: " + jsonArray);

        // Cập nhật giá trị của trường "lastname" trong phần tử đầu tiên
        if (jsonArray.size() > 0) {
            //Lấy vị trí object thứ nhất
            JsonObject firstObject = jsonArray.get(0).getAsJsonObject();
            firstObject.addProperty("lastname", "NewLastName");
        }

        System.out.println("Modified JSON: " + jsonArray);

        //Store new Json data to old file
        File jsonFile = new File("src/test/resources/testdata/TestJsonFile03.json");
        OutputStream outputStream = new FileOutputStream(jsonFile);
        //Lưu đối tượng jsonArray chứ không phải jsonObject
        outputStream.write(gson.toJson(jsonArray).getBytes());
        outputStream.flush();

        //Close reader
        reader.close();

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}



🔆 Cập nhật giá trị của field trong object con

Giờ chúng ta muốn cập nhật giá trị của field "checkout" thì nó nằm trong field cha là "bookingdates" nên không thể dùng cách trên được.

Chúng ta sẽ dùng hàm getAsJsonObject để tìm thuộc tính cha trước sau đó mới add thuộc tính con vào sau.

jsonObject.getAsJsonObject("bookingdates").addProperty("checkout", "new_checkout_date");


Code thực thi xong lưu vào chính file JSON cũ luôn

@Test
public void testUpdateValueInJson02() {

    Reader reader;
    String filePath = "src/test/resources/testdata/TestJsonFile01.json";

    try {
        reader = Files.newBufferedReader(Paths.get(filePath));

        Gson gson = new Gson();
        //Convert Json file to Json Object
        JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
        System.out.println("Original JSON: " + jsonObject);

        // Cập nhật giá trị của trường "checkout"
        jsonObject.getAsJsonObject("bookingdates").addProperty("checkout", "2024-04-10");

        System.out.println("Modified JSON: " + jsonObject);

        //Store new Json data to old file
        File jsonFile = new File("src/test/resources/testdata/TestJsonFile01.json");
        OutputStream outputStream = new FileOutputStream(jsonFile);
        outputStream.write(gson.toJson(jsonObject).getBytes());
        outputStream.flush();

        //Close reader
        reader.close();

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Kết quả:

{
   "firstname": "Anh",
   "lastname": "Tester",
   "totalprice": 111,
   "depositpaid": true,
   "bookingdates": {
      "checkin": "2023-12-28",
      "checkout": "2024-04-10"
   },
   "additionalneeds": "Technology"
}

 

✅ Chỉnh sửa thuộc tính trong JSON file

Chúng ta sẽ add thêm các cặp key value mới, xoá key hoặc chỉnh sửa tên key (tên field).

🔆 Add new Property

@Test
public void testAddNewPropertyInJson() {

    Reader reader;
    String filePath = "src/test/resources/testdata/TestJsonFile01.json";

    try {
        reader = Files.newBufferedReader(Paths.get(filePath));

        Gson gson = new Gson();
        //Convert Json file to Json Object
        JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
        System.out.println("Original JSON: " + jsonObject);

        //Create array value
        JsonArray objectArray = new JsonArray();
        objectArray.add("Support");
        objectArray.add("ERP");

        //Add array value to key "department"
        jsonObject.add("department", objectArray);

        //Add simple key:value
        jsonObject.addProperty("key1", "Value for Key1");

        //Add key:{object}
        Map < String, Object > objectMap = new HashMap < > ();
        objectMap.put("name", "Anh Tester");
        objectMap.put("age", 27);
        JsonElement jsonElement = gson.toJsonTree(objectMap);
        jsonObject.add("student", jsonElement);

        System.out.println("Modified JSON: " + jsonObject);

        //Store new Json data to old file
        File jsonFile = new File("src/test/resources/testdata/TestJsonFile01Edited.json");
        OutputStream outputStream = new FileOutputStream(jsonFile);
        outputStream.write(gson.toJson(jsonObject).getBytes());
        outputStream.flush();

        //Close reader
        reader.close();

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

 

🔆 Remove Property

Giả sử chúng ta muốn Remove key "age" và key "years"

TestJsonFile02.json

{
   "name": "Bob",
   "age": 23,
   "department": {
      "name": "IT",
      "position": {
         "role": "lead",
         "years": 3
      }
   }
}

 

@Test
public void testRemovePropertyInJson() {

    Reader reader;
    String filePath = "src/test/resources/testdata/TestJsonFile02.json";

    try {
        reader = Files.newBufferedReader(Paths.get(filePath));

        Gson gson = new Gson();
        //Convert Json file to Json Object
        JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
        System.out.println("Original JSON: " + jsonObject);

        jsonObject.remove("age");

        //Xác định vị trí của property cần xoá
        JsonObject positionObject = jsonObject
            .get("department").getAsJsonObject()
            .get("position").getAsJsonObject();

        //Xoá key "years" trong cấu trúc propert
        positionObject.remove("years");

        System.out.println("Modified JSON: " + jsonObject);

        //Store new Json data to new file
        File jsonFile = new File("src/test/resources/testdata/TestJsonFile02Edited.json");
        OutputStream outputStream = new FileOutputStream(jsonFile);
        outputStream.write(gson.toJson(jsonObject).getBytes());
        outputStream.flush();

        //Close reader
        reader.close();

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Kết quả:

{
   "name": "Bob",
   "department": {
      "name": "IT",
      "position": {
         "role": "lead"
      }
   }
}

Teacher

Teacher

Anh Tester

Software Quality Engineer

Đường dẫu khó chân vẫn cần bước đi
Đời dẫu khổ tâm vẫn cần nghĩ thấu

Cộng đồng Automation Testing Việt Nam:

🌱 Telegram Automation Testing:   Cộng đồng Automation Testing
🌱 
Facebook Group Automation: Cộng đồng Automation Testing Việt Nam
🌱 
Facebook Fanpage: Cộng đồng Automation Testing Việt Nam - Selenium
🌱 Telegram
Manual Testing:   Cộng đồng Manual Testing
🌱 
Facebook Group Manual: Cộng đồng Manual Testing Việt Nam

Chia sẻ khóa học lên trang

Bạn có thể đăng khóa học của chính bạn lên trang Anh Tester để kiếm tiền

Danh sách bài học