Skip to content

Commit

Permalink
Update bài 6 - POJO class to JSON body
Browse files Browse the repository at this point in the history
  • Loading branch information
anhtester committed Dec 14, 2023
1 parent 389f0fa commit dd47e37
Show file tree
Hide file tree
Showing 16 changed files with 675 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,12 @@ buildNumber.properties
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
*.iml
.idea/
reports/
report/
out/
logs/
*.log
*.avi
*.mp4
55 changes: 55 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.anhtester</groupId>
<artifactId>RestAssuredTestNG2023</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>

<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.9</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>

</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.anhtester.Bai3_SendRequest_GET;

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

import static io.restassured.RestAssured.given;

public class DemoAddHeader {

@Test
public void testAddHeader(){

//Khai báo đối tượng request
RequestSpecification request = given();
request.baseUri("https://api.anhtester.com/api");
request.basePath("/users");
//Add header theo yêu cầu, với cú pháp (key,value)
request.header("accept", "application/json");
//request.header("", "");
//request.accept("application/json");

Response response = request.when().get();

response.prettyPrint();

response.then().statusCode(200);

}

}
39 changes: 39 additions & 0 deletions src/test/java/com/anhtester/Bai3_SendRequest_GET/DemoAddParam.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.anhtester.Bai3_SendRequest_GET;

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

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

public class DemoAddParam {

@Test
public void testUserByUserName() {
//Khai báo đối tượng request để thiết lập điều kiện đầu vào
//Dùng given() chỉ thị sự thiết lập sẵn điều kiện
RequestSpecification request = given();
request.baseUri("https://api.anhtester.com/api")
.basePath("/user")
.accept("application/json");

//Khai báo tham số đầu vào với hàm queryParam
request.queryParam("username", "anhtester2");
// request.pathParam("", "");
// request.formParam("", "");

Response response = request.when().get();
response.prettyPrint();

response.then().statusCode(200);
response.then().statusLine("HTTP/1.1 200 OK");
response.then().contentType(ContentType.JSON);

response.then().body("response.username", equalTo("anhtester2"));
response.then().body("response.email", containsString("an2"));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.anhtester.Bai3_SendRequest_GET;

import io.restassured.http.ContentType;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;

public class DemoGivenWhenThen {

@Test
public void testGetUsers(){
System.out.println("testGetUsers");

given().baseUri("https://api.anhtester.com/api")
.accept("application/json")
.basePath("/users")
.when().get()
.then().statusCode(200).contentType(ContentType.JSON);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.anhtester.Bai4_VerifyResponse;

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

import static io.restassured.RestAssured.given;

public class DemoVerifyUseAssertTestNG {
@Test
public void testVerifyResponseUseAssertTestNG() {
RequestSpecification request = given();
request.baseUri("https://api.anhtester.com/api")
.accept("application/json");

int id = 1; //ID của book. Gắn vào sau path url luôn

Response response = request.when().get("/book/" + id);
response.prettyPrint();

//Verify kết quả từ response với Assert trong TestNG
//Dùng class Assert chấm gọi 2 hàm chính là assertEquals và assertTrue
Assert.assertEquals(response.getStatusCode(), 200, "Status Code chưa đúng.");
Assert.assertEquals(response.getContentType(), "application/json", "Content Type chưa đúng.");

//Khi lấy kết quả trong body thì cần dùng đối tượng class ResponseBody để lấy hết về kiểu String
//Khi đó chỉ có thể dùng hàm contains để so sánh chứa, vì không lấy được từng giá trị của từng key
ResponseBody body = response.getBody();
Assert.assertEquals(body.asString().contains("Success"), true, "Message Success không tồn tại.");

//Muốn lấy giá trị từng key trong JSON body để compare chính xác thì
//phải dùng hàm then() hoặc thư viện JsonPath
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.anhtester.Bai4_VerifyResponse;

import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.testng.Assert;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;

public class DemoVerifyUseJsonPath {
@Test
public void testVerifyResponseUseAssertTestNG() {
RequestSpecification request = given();
request.baseUri("https://api.anhtester.com/api")
.accept("application/json");

int id = 1; //ID của book. Gắn vào sau path url luôn

Response response = request.when().get("/book/" + id);
response.prettyPrint();

//Verify kết quả từ response với Assert trong TestNG
//Dùng class Assert chấm gọi 2 hàm chính là assertEquals và assertTrue
Assert.assertEquals(response.getStatusCode(), 200, "Status Code chưa đúng.");
Assert.assertEquals(response.getContentType(), "application/json", "Content Type chưa đúng.");

//Muốn lấy giá trị từng key trong JSON body để compare chính xác thì dùng JsonPath
JsonPath jsonPath = response.jsonPath(); //Lưu hết body vào đối tượng jsonPath

//Truy xuất giá trị theo key hoặc đường dẫn xpath theo cấp bậc
String name = jsonPath.get("response.name");
System.out.println("Name: " + name);
//Dùng Assert của TestNG để verify
Assert.assertEquals(name.contains("Phương Nam"), true, "Name không tồn tại.");
Assert.assertEquals(name, "Đất Rừng Phương Nam", "Name không tồn tại.");
//Khi lấy trực tiếp giá trị từ jsonPath thì cần toString
//và phải chuyển số về sạng chuỗi để so sánh
Assert.assertEquals(jsonPath.get("response.price").toString(), "12000", "Price không đúng.");
Assert.assertEquals(Integer.parseInt(jsonPath.get("response.price").toString()), 12000, "Price không đúng.");

//Lấy đường dẫn path thứ 2 trong mảng của object "image"
//Index bắt đầu tính từ 0
String imagePath2 = jsonPath.get("response.image[1].path");
System.out.println(imagePath2);
Assert.assertTrue(imagePath2.contains("public/images/TwSX1W1"), "Không đúng hình ảnh thứ 2.");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.anhtester.Bai4_VerifyResponse;

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

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

public class DemoVerifyUseThenMethod {

@Test
public void testVerifyResponseUseThenMethod() {
RequestSpecification request = given();
request.baseUri("https://api.anhtester.com/api")
.accept("application/json");

int id = 1; //ID của book. Gắn vào sau path url luôn

Response response = request.when().get("/book/" + id);
response.prettyPrint();

//Verify kết quả từ response với hàm then()
response.then().statusCode(200);
response.then().contentType("application/json");
//Đối với body thì cần điền cấu trúc theo xpath từ json
//Hàm equalTo thuộc thư viện org.hamcrest.Matchers
response.then().body("response.name", equalTo("Đất Rừng Phương Nam"));
response.then().body("response.price", equalTo(1200));
//Dùng vị trí index để lấy thứ tự phần tử trong JSON body. Tính từ 0
response.then().body("response.image[0].path", containsString("public/images/1avh0VncWc"));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.anhtester.Bai5_PhuongThucPOST;

import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.File;

import static io.restassured.RestAssured.given;

public class DemoPostMethod {
@Test
public void testLoginUser() {
RequestSpecification request = given();
request.baseUri("https://api.anhtester.com/api")
.accept("application/json")
.contentType("application/json")
.body("{\n" +
" \"username\": \"anhtester4\",\n" +
" \"password\": \"Demo@123\"\n" +
"}");

//Thực hiện phương thức post() để gửi dữ liệu đi
Response response = request.when().post("/login");
response.prettyPrint();

response.then().statusCode(200);

String token = response.getBody().path("token").toString();
System.out.println(token);
}

@Test
public void testRegisterUser() {

String username = "anhtester12";
String firstName = "Anh";
String lastName = "Tester";
String email = username + "@email.com";
String password = "Demo@123";
String phone = "0123456789";
int userStatus = 1;

RequestSpecification request = given();
request.baseUri("https://api.anhtester.com/api")
.accept("application/json")
.contentType("application/json")
.body("{\n" +
" \"username\": \" " + username + "\",\n" +
" \"firstName\": \"" + firstName + "\",\n" +
" \"lastName\": \"" + lastName + "\",\n" +
" \"email\": \"" + username + "@email.com\",\n" +
" \"password\": \"" + password + "\",\n" +
" \"phone\": \"" + phone + "\",\n" +
" \"userStatus\": " + userStatus + "\n" +
"}");

//Thực hiện phương thức post() để gửi dữ liệu đi
Response response = request.when().post("/register");
response.prettyPrint();
response.then().statusCode(200);

//Verify Response
response.then().contentType(ContentType.JSON);

//Cách 1
ResponseBody responseBody = response.getBody();

//Cách 2 (ưu tiên cách 2)
JsonPath jsonPath = response.jsonPath();

Assert.assertEquals(jsonPath.get("response.username"), username, "The username not match.");
Assert.assertEquals(responseBody.path("response.firstName"), firstName, "The firstName not match.");
Assert.assertEquals(responseBody.path("response.lastName"), lastName, "The lastName not match.");
Assert.assertEquals(responseBody.path("response.email"), email, "The email not match.");
//Assert.assertEquals(responseBody.path("response.password"), password, "The password not match.");
Assert.assertEquals(responseBody.path("response.phone"), phone, "The phone not match.");
Assert.assertEquals(Integer.parseInt(responseBody.path("response.userStatus").toString()), userStatus, "The userStatus not match.");
Assert.assertTrue(responseBody.path("response.id").toString().length() > 0, "The ID not exsiting.");

}
}
Loading

0 comments on commit dd47e37

Please sign in to comment.