Trang chủ · Blog về kiểm thử ·
Checklist kiểm thử REST API: kiểm tra thực tế, ví dụ và câu trả lời phỏng vấn
“Gửi mọi method rồi check status” không phải chiến lược test API. Một phép kiểm hữu ích phải nối contract, input partition, permission, persisted state và downstream effect. Bài này dựng mô hình đó quanh order endpoint và cách giải thích trong QA interview.
- Model resource và rule
- Chuẩn bị actor và data
- Gửi positive/negative request
- Kiểm response, state và effect
| Lớp | Câu hỏi | Evidence |
|---|---|---|
| Transport | HTTP đúng contract không? | Status, header, content type, timing |
| Contract | Response structure hợp lệ không? | Required field, type, format, error schema |
| Business | Value và transition đúng không? | Total, ownership, limit, status transition |
| State | Thứ gì thật sự được lưu? | Follow-up GET, database hoặc event |
| Integration | Ngoài service đã xảy ra gì? | Payment, queue, email, retry, reconciliation |
1. Biến documentation thành test model
Bắt đầu từ resource, không phải tool. Với POST /orders, xác định ai được gọi, header bắt buộc, request field và constraint, success response, error format và state của order sau khi tạo. Rule chưa rõ phải thành câu hỏi, không lấy current behavior làm expected result.
Tạo decision table cho authenticated/anonymous, cart empty/not empty, stock đủ/không đủ và payment required/not required. Nó tìm combination mà danh sách endpoint phẳng bỏ sót. Ghi environment và API version.
- Nêu business invariant của endpoint.
- Tách documented rule khỏi assumption.
- Ghi version, environment và test-data owner.
- Nối mỗi response với state transition đã hứa.
Bài thực hành
Lập decision table cho POST /orders theo auth, empty cart và stock. Đếm meaningful combinations.
2. Method, status code, header và content negotiation
HTTP semantics là một phần contract. GET safe; PUT và DELETE được định nghĩa idempotent; POST không tự động idempotent. Hãy test ý nghĩa của repeat trong sản phẩm, không chỉ học thuộc status. 200 kèm error object vẫn có thể sai contract.
Kiểm Content-Type, Location sau create khi contract yêu cầu, cache header và correlation id. Phân biệt 400 syntax, 401 authentication, 403 permission, 404 missing resource, 409 state conflict và 422 semantic validation theo contract thật.
POST /orders HTTP/1.1
Authorization: Bearer <token>
Content-Type: application/json
Idempotency-Key: order-77-cart-19
{"delivery_address_id": 55}
Bài thực hành
Định nghĩa response cho missing token, expired token và valid token thiếu permission; không gom mọi trường hợp vào 401.
3. Input validation và test design
Áp dụng equivalence partition và boundary cho từng rule. Quantity 1–10 cần 0, 1, 10, 11, wrong type, missing, NULL và decimal. String cần empty, whitespace, length, encoding và normalization. Không tạo hàng chục random value cùng một partition.
Kiểm cả cross-field và state rule: coupon đúng format có thể expired, address hợp lệ có thể thuộc user khác, product id hợp lệ có thể hết stock. Error phải chỉ ra rule mà không lộ stack trace hay SQL.
valid: {"quantity": 1}, {"quantity": 10}
invalid: {"quantity": 0}, {"quantity": 11}
type: {"quantity": "2"}, {"quantity": 2.5}
missing: {}, {"quantity": null}
Bài thực hành
Chia email thành valid và invalid partition, gồm case normalization và duplicate registration.
4. Kiểm schema, value và persisted state
Schema validation xác nhận required field, type và format; nó không chứng minh total đúng hoặc record đã được lưu. Hãy tính business oracle độc lập theo rounding rule đã thống nhất.
Sau write, đọc lại qua interface hỗ trợ. POST trả 1242 nhưng GET trả 1380 gợi ý lỗi persistence/read model. Cả hai trả 1242 nhưng provider charge 1380 thì lỗi downstream. Hai quan sát cần hai báo cáo khác nhau.
pm.test('created', () => pm.response.to.have.status(201));
pm.test('json response', () => pm.expect(pm.response.headers.get('Content-Type')).to.include('application/json'));
const order = pm.response.json();
pm.test('expected total', () => pm.expect(order.total).to.eql(1242));
pm.environment.set('order_id', order.id);
Bài thực hành
Thiết kế response/follow-up check cho việc convert CRM lead thành customer, gồm repeated conversion.
5. Authentication, authorization và ownership
Authentication trả lời caller là ai; authorization trả lời họ được làm gì. Kiểm no token, malformed/expired token, wrong role và truy cập object người khác. Ẩn button trên UI không bảo vệ API.
Tạo hai synthetic user. A tạo order; B thử GET, PATCH, DELETE bằng id của A. Kiểm cả list, search, export và nested resource vì detail endpoint kín vẫn có thể đi cùng search bị leak.
Actor A + order A: GET allow, PATCH allow Actor B + order A: GET deny, PATCH deny Admin + order A: theo documented role Anonymous : deny, không leak data
Bài thực hành
Tạo actor/action matrix cho CRM customer thuộc một manager và supervisor được phép xem.
6. Idempotency, retry, concurrency và pagination
Client retry sau timeout, proxy lặp call và user double-click. Gửi lại request với cùng và khác idempotency key rồi kiểm final business effect. Chạy song song cho coupon, lead conversion hoặc last stock item.
Với pagination, kiểm stable order, không overlap/gap, metadata và page-size boundary. Rate limit cần limit−1, limit, limit+1 cùng header/reset, không chỉ tạo một 429.
- Cùng key và cùng body.
- Cùng key nhưng khác body.
- Timeout trước khi client thấy response.
- Hai request bắt đầu đồng thời.
- Hai phía của rate-limit boundary.
Bài thực hành
Thiết kế test hai user mua sản phẩm cuối cùng. Nêu allowed outcome và stock invariant.
7. Dependency failure và asynchronous processing
API có thể trả trước khi queue consumer, payment provider hoặc email service hoàn tất. Tách accepted work khỏi completed work; định nghĩa status polling, event hoàn tất, eventual-consistency window và deadline.
Mô phỏng timeout, 5xx, malformed response, duplicate/out-of-order event và queue unavailable. Kiểm retry, dead-letter, idempotent consumer và reconciliation. Publish message chưa chứng minh notification đã được gửi.
POST /exports -> 202 + export_id
GET /exports/{id} -> queued | processing | ready | failed
ready -> download URL hoạt động và thuộc requester
failed -> reason an toàn, retry quan sát được
Bài thực hành
Vẽ state của order, payment và email confirmation; nêu owner system và evidence cho từng transition.
8. Performance, automation và test report hữu ích
Performance check cần workload và threshold: concurrency/RPS, data volume, warm-up, percentile và error budget. “API nhanh” không đo được. Theo dõi p95/p99 cùng error rate và saturation.
Automate check ổn định và có giá trị: contract, critical rule, authorization matrix và regression path. Isolate data, tránh chain dài che failure đầu tiên, và report request id, sanitized request/response, environment, expected state và side effect.
- Fast contract tests cho mỗi change.
- Integration tests cho storage/dependency.
- Critical smoke nhỏ sau deployment.
- Regression theo changed risk.
- Observability cho latency, error và queue.
Bài thực hành
Biến năm check trong bài thành CI suite; với mỗi check nêu setup, assertion, cleanup và failure evidence.
Câu hỏi thường gặp về REST API testing
Postman có đủ để test API không?
Postman là client hữu ích, nhưng kỹ năng thật là model contract, data, risk và side effect. Cùng phép kiểm có thể chạy bằng client khác hoặc automation framework.
Mọi endpoint có dùng cùng checklist không?
Dùng baseline chung cho transport, contract, validation và auth, rồi thêm check theo risk. Payment, search và async export cần độ sâu khác nhau.
Mỗi API error có cần status code riêng không?
Không có mapping chung cho mọi sản phẩm. Điều quan trọng là contract nhất quán giúp client phân biệt auth, permission, validation, missing resource và conflict mà không leak internals.
Làm sao biết API coverage đủ?
Map test với rule, transition, actor, input partition, integration và risk. Endpoint count hay code coverage riêng lẻ không chứng minh business behavior quan trọng đã được bảo vệ.
API test mạnh đi xa hơn response đầu tiên. Nó giải thích rule, actor và data đã kiểm, final state mong đợi và uncertainty còn lại.