Pengantar API Testing: Menjaga Kontrak dan Integritas Layanan
Pengantar API Testing: Menjaga Kontrak dan Integritas Layanan
Mengapa API Testing?
API adalah kontrak antar layanan. Pengujian API memastikan kontrak stabil, data benar, dan kesalahan ditangani.
Jenis
- Contract testing: schema-first, backward compatibility.
- Functional: respons, status, validasi bisnis.
- Negative: error handling, throttling, auth.
- Performance: latency, throughput, saturasi.
Praktik Baik
- Versikan API; uji kompatibilitas mundur.
- Gunakan data deterministik dan idempotensi.
- Mock dependensi eksternal untuk skenario tepi.
Contoh (JavaScript, supertest + Express)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// app.js
import express from 'express';
const app = express();
app.get('/health', (_, res) => res.json({ ok: true }));
export default app;
// app.test.js
import request from 'supertest';
import app from './app';
it('returns health ok', async () => {
const res = await request(app).get('/health');
expect(res.status).toBe(200);
expect(res.body).toEqual({ ok: true });
});
Postman/Newman (CLI)
- Simpan koleksi Postman dan jalankan di CI dengan:
npx newman run collection.json -e env.json.
Contract Testing (Pact, contoh ringkas)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// consumer.pact.test.js
import path from 'path';
import { Pact } from '@pact-foundation/pact';
const provider = new Pact({
consumer: 'WebApp',
provider: 'CatalogService',
dir: path.resolve(process.cwd(), 'pacts')
});
test('get product by id', async () => {
await provider.setup();
await provider.addInteraction({
state: 'product 123 exists',
uponReceiving: 'a request for product 123',
withRequest: { method: 'GET', path: '/products/123' },
willRespondWith: { status: 200, headers: { 'Content-Type': 'application/json' }, body: { id: '123' } }
});
// panggil client dan verifikasi
await provider.verify();
await provider.finalize();
});
Negative Testing (contoh)
- Auth: token kadaluarsa → 401 dengan payload error standar.
- Rate limit: >N request/menit → 429 dengan header
Retry-After.
This post is licensed under CC BY 4.0 by the author.