← 課程地圖

TESTING CORE · 121

API Integration Test:真的走過 Route、Auth、Service、Database

Integration test 的價值是驗證真實 components 的協作:HTTP route、body parsing、validation、auth、business rule、database constraint/RLS 與 response mapping。

Learning outcomes

1. 測試路徑

HTTP request
  ↓
route / middleware
  ↓
validation / auth
  ↓
service
  ↓
test database
  ↓
constraint / RLS
  ↓
HTTP response

2. 一個 POST test 不只看 201

Arrange:
  user A
  empty test DB

Act:
  POST /courses

Assert:
  status = 201
  body shape
  DB row exists
  owner_id = user A

3. Test data isolation

每個 test 應建立自己需要的資料,不依賴某位 developer 手工先塞 row。常見策略包括 transaction rollback、fresh schema、fixture factory 等。

4. Production DB 禁止當沙盒

Integration tests 應使用隔離環境。Test 會建立/刪除/污染資料,不應對 production 執行。

5. RLS test matrix

user A reads A row      PASS
user A reads B row      DENY
user B updates B row    PASS
anon reads private      DENY
privileged operation    explicit test

Project checkpoint:Course API integration suite

POST /courses
  valid → 201
  invalid → 400
  no auth → 401
  duplicate → 409

GET /courses/:id
  owner → 200
  other user → denied/not visible
  missing → 404

Debug evidence:test fail 在哪層?

Integration test failure 需要看 request log、authenticated user、DB row、constraint/RLS error,不要只看最後 status。

Knowledge check

  1. Integration test 和 unit test 最大差別?
  2. 為什麼 production DB 不可直接拿來測?
  3. RLS 為什麼必須用多 user context?
  4. 替 POST /courses 設計 5 個 integration cases。