การทดสอบ API
การทดสอบคือสิ่งที่ให้คุณเปลี่ยนแปลง API ได้อย่างมั่นใจ สามชั้น แต่ละชั้นดักจับบั๊กคนละประเภท ให้ความครอบคลุมที่ดีโดยไม่ต้องลงแรงซ้ำซ้อน
ชั้นต่าง ๆ
หัวข้อที่มีชื่อว่า “ชั้นต่าง ๆ”flowchart TD U[Unit: handlers, validation, pure logic - many, fast] --> I[Integration: real routes end-to-end - fewer] I --> C[Contract: responses match the OpenAPI spec - focused]
- Unit tests — ทดสอบชิ้นส่วนล้วน ๆ เช่น validator, ตัวช่วย pagination, ตัว map error เร็วและมีจำนวนมาก
- Integration tests — ส่ง request จริงผ่าน router ตัวจริงแล้วตรวจสอบ status, header และ body สิ่งเหล่านี้ดักจับบั๊กการเชื่อมต่อที่ unit test มองข้าม
- Contract tests — ตรวจสอบว่า response สอดคล้องกับ schema ของ OpenAPI เพื่อให้การสร้างจริงและ contract ที่เผยแพร่ไปไม่มีวันคลาดเคลื่อนกัน
การ assert แบบ integration
หัวข้อที่มีชื่อว่า “การ assert แบบ integration”เฟรมเวิร์กอย่าง Hono เปิดให้ใช้ app.request(...) คุณจึงเรียก route แบบ in-process ได้โดยไม่ต้องผ่าน network
ควร assert อะไรบ้าง
หัวข้อที่มีชื่อว่า “ควร assert อะไรบ้าง”แต่ละ endpoint ให้ทดสอบทั้ง happy path และ failure path ได้แก่ status code ที่ถูกต้อง รูปร่างของ response error body ของ input ที่ไม่ถูกต้อง (ตรงกับ problem+json ของคุณหรือเปล่า) การบังคับ auth ในจุดที่ควรมี และ metadata ของ pagination บน collection
| Test Type | ทดสอบอะไร | เหมาะกับ |
|---|---|---|
| Unit test | logic ใน function แยก | validation, business rule |
| Integration test | endpoint จริง + database จริง | happy path, error path |
| Contract test | request/response match OpenAPI spec | API evolution |
| E2E test | user journey ทั้งหมด | critical flow เช่น checkout |
ข้อผิดพลาดที่พบบ่อย
หัวข้อที่มีชื่อว่า “ข้อผิดพลาดที่พบบ่อย”Test เฉพาะ Happy Path อาการ:
- test ที่ pass request ถูกต้อง — resource สร้าง, status 201
- ไม่ test: validation error, auth failure, not found, conflict
- test error path ทุก status code ที่ API document ไว้
Mock Database ใน Integration Test อาการ:
- integration test mock database — query จริงไม่ได้รัน
- SQL ผิด, constraint ผิด — pass ใน test แต่ fail ใน production
- ใช้ test database จริง (SQLite in-memory หรือ test container)
💡 ตัวอย่างจากของจริง
Stripe:
- test mode API key — รัน test บน Stripe environment จริงโดยไม่ charge จริง
- webhook testing ผ่าน Stripe CLI:
stripe listen --forward-to localhost:3000/webhookGitHub:
- API test ผ่าน sandbox environment
- contract test ด้วย OpenAPI spec — CI fail ถ้า response ไม่ match spec