Dưới đây là một số cách bạn có thể viết script để assert giá trị trong response trên Postman:
1. Assert giá trị cụ thể trong JSON response:
pm.test("Kiểm tra giá trị 'name' trong response", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.name).to.eql("John Doe");
});
pm.response.json(): Chuyển đổi response body thành đối tượng JSON.pm.expect(jsonData.name).to.eql("John Doe"): Assert rằng giá trị của thuộc tính "name" trong JSON response bằng "John Doe".
2. Assert status code:
pm.test("Kiểm tra status code là 200", function () {
pm.response.to.have.status(200);
});
pm.response.to.have.status(200): Assert rằng status code của response là 200 (OK).
3. Assert giá trị của header:
pm.test("Kiểm tra header 'Content-Type' là 'application/json'", function () {
pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json');
});
pm.response.headers.get('Content-Type'): Lấy giá trị của header "Content-Type".pm.expect(...).to.eql('application/json'): Assert rằng giá trị header bằng "application/json".
4. Assert một phần của response body:
pm.test("Kiểm tra response body chứa 'success'", function () {
pm.expect(pm.response.text()).to.include("success");
});
pm.response.text(): Lấy response body dưới dạng text.pm.expect(...).to.include("success"): Assert rằng response body chứa chuỗi "success".
5. Assert kiểu dữ liệu của một giá trị trong JSON response:
pm.test("Kiểm tra 'age' là kiểu số", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.age).to.be.a('number');
});
pm.expect(jsonData.age).to.be.a('number'): Assert rằng giá trị của thuộc tính "age" là kiểu số.
6. Assert một mảng trong JSON response có độ dài cụ thể:
pm.test("Kiểm tra mảng 'items' có 3 phần tử", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.items).to.have.lengthOf(3);
});
pm.expect(jsonData.items).to.have.lengthOf(3): Assert rằng mảng "items" có độ dài là 3.
7. Assert một giá trị trong JSON response thỏa mãn một điều kiện:
pm.test("Kiểm tra 'age' lớn hơn 18", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.age).to.be.above(18);
});
pm.expect(jsonData.age).to.be.above(18): Assert rằng giá trị của thuộc tính "age" lớn hơn 18.
Lưu ý:
pm.expect(jsonData.age).to.be.below(100) (nhỏ hơn), pm.expect(jsonData.age).to.be.at.least(18) (lớn hơn hoặc bằng), và pm.expect(jsonData.age).to.be.at.most(65) (nhỏ hơn hoặc bằng).
Hy vọng những ví dụ này sẽ giúp bạn viết script assert giá trị trong response trên Postman một cách hiệu quả.
🌱 Facebook
Fanpage: Anh Tester
🌱
Telegram Automation Testing:
Cộng đồng Automation Testing
🌱 Facebook Group Automation:
Cộng đồng Automation
Testing Việt Nam
🌱
Telegram Manual Testing:
Cộng đồng Manual Testing
🌱 Facebook
Group Manual:
Cộng đồng Manual Testing Việt Nam
Copyright © 2021-2025 Anh Tester Automation Testing
Anh Tester
Đườ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