Golang Testing Strategy: Unit Test, Integration Test, E2E dari Spec
Testing strategy lengkap Santekno Shop. Unit test dengan testify + gomock, integration test dengan real PostgreSQL, E2E test dengan Prism mock server — semua derive dari spec ACs.
Golang testing strategy yang baik bukan afterthought — di Santekno Shop setiap acceptance criteria (AC) dari spec punya test yang mengkovernya. Kita sudah menulis sebagian besar testnya di Artikel 06-10, tapi di artikel ini kita formalisasi strateginya: struktur direktori, test harness, dan cara menjalankan setiap layer secara terpisah agar traceable balik ke spec.
16.01 Testing Pyramid Santekno Shop
Sebelum menulis satu test pun, kita perlu peta proporsi: berapa banyak test di tiap layer dan seberapa cepat mereka berjalan. Diagram piramida berikut merangkum pembagiannya di Santekno Shop.
1 ┌─────────────────┐
2 │ E2E Tests │ ← 5-10 happy paths
3 │ (Prism + real) │ ~20 test cases
4 ─┴─────────────────┴─
5 ┌─────────────────────────────┐
6 │ Integration Tests │ ← Repository layer
7 │ (real PostgreSQL + Redis) │ ~50 test cases
8 ─┴─────────────────────────────┴─
9 ┌─────────────────────────────────────────┐
10 │ Unit Tests │ ← UseCase + Entity
11 │ (mocks, no external dependencies) │ ~150 test cases
12 ─┴─────────────────────────────────────────┴─
13
14Strategy:
15 Unit → fast (< 1ms), test business logic in isolation
16 Integration → medium (100ms-5s), test DB queries and transactions
17 E2E → slow (1-30s), test full HTTP flow end to endPrinsipnya: mayoritas test ada di layer unit yang cepat, dan hanya sedikit E2E yang mahal — sehingga feedback loop tetap kilat tanpa mengorbankan cakupan.
16.02 Test Naming Convention dari Spec
Nama test yang baik langsung memberi tahu AC mana yang di-cover tanpa perlu buka spec. Pola penamaan berikut membuat setiap test function traceable ke acceptance criteria-nya.
1// Format: Test[UseCase]_[Scenario]_[ExpectedResult]
2// Langsung traceable ke Spec AC
3
4// Dari spec: place-order AC2 "insufficient stock → 422"
5func (s *PlaceOrderSuite) TestPlaceOrder_InsufficientStock_Returns422() { ... }
6
7// Dari spec: cancel-order AC3 "window expired → 409"
8func (s *CancelOrderSuite) TestCancelOrder_WindowExpired_Returns409() { ... }
9
10// Dari spec: user-login AC4 "rate limit → 429"
11func (s *LoginUserSuite) TestLoginUser_RateLimitExceeded_Returns429() { ... }
12
13// Template:
14// Test[Domain+UseCase]_[Condition from AC]_[Expected HTTP or domain error]Dengan konvensi ini, ketika sebuah test gagal, kamu langsung tahu AC mana yang regres — bukan sekadar “ada test merah”.
16.03 Test Suite Structure dengan testify/suite
Untuk mengelompokkan test satu usecase dan berbagi setup, kita pakai testify/suite. Struktur berikut menyiapkan mock segar di setiap test lewat SetupTest dan memverifikasi ekspektasi di TearDownTest.
1// internal/usecase/order/place_order_test.go
2
3package order_test
4
5import (
6 "context"
7 "testing"
8 "time"
9
10 "github.com/google/uuid"
11 "github.com/stretchr/testify/suite"
12 "go.uber.org/mock/gomock"
13
14 domainOrder "github.com/santekno/santekno-shop/internal/domain/order"
15 domainProduct "github.com/santekno/santekno-shop/internal/domain/product"
16 orderUC "github.com/santekno/santekno-shop/internal/usecase/order"
17 "github.com/santekno/santekno-shop/testutil/mock"
18)
19
20// PlaceOrderSuite: semua test untuk PlaceOrder usecase dalam satu suite
21type PlaceOrderSuite struct {
22 suite.Suite
23 ctrl *gomock.Controller
24 orderRepo *mock.MockOrderRepository
25 productRepo *mock.MockProductRepository
26 publisher *mock.MockPublisher
27 uc *orderUC.PlaceOrderUseCase
28 // Fixed test data
29 userID uuid.UUID
30 productID uuid.UUID
31}
32
33func (s *PlaceOrderSuite) SetupTest() {
34 s.ctrl = gomock.NewController(s.T())
35 s.orderRepo = mock.NewMockOrderRepository(s.ctrl)
36 s.productRepo = mock.NewMockProductRepository(s.ctrl)
37 s.publisher = mock.NewMockPublisher(s.ctrl)
38 s.uc = orderUC.NewPlaceOrderUseCase(s.orderRepo, s.productRepo, s.publisher)
39 s.userID = uuid.New()
40 s.productID = uuid.New()
41}
42
43func (s *PlaceOrderSuite) TearDownTest() {
44 s.ctrl.Finish()
45}
46
47// Helper: build valid product mock
48func (s *PlaceOrderSuite) mockProduct(stock, reserved int) *domainProduct.Product {
49 return &domainProduct.Product{
50 ID: s.productID, Name: "Test Product",
51 PriceIDR: 100_000_00, Stock: stock, ReservedStock: reserved, IsActive: true,
52 }
53}
54
55// Helper: build valid order input
56func (s *PlaceOrderSuite) validInput(qty int) orderUC.PlaceOrderInput {
57 return orderUC.PlaceOrderInput{
58 UserID: s.userID,
59 Items: []orderUC.PlaceOrderItem{{ProductID: s.productID, Quantity: qty}},
60 PaymentMethod: domainOrder.PaymentQRIS,
61 }
62}
63
64// AC1: Berhasil buat order
65func (s *PlaceOrderSuite) TestPlaceOrder_ValidItems_Creates201Order() {
66 s.productRepo.EXPECT().GetByID(gomock.Any(), s.productID.String()).
67 Return(s.mockProduct(10, 0), nil)
68 s.orderRepo.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil)
69 s.publisher.EXPECT().Publish(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
70
71 order, err := s.uc.Execute(context.Background(), s.validInput(2))
72 s.NoError(err)
73 s.NotNil(order)
74 s.Equal(domainOrder.StatusPending, order.Status)
75 s.Equal(int64(200_000_00), order.TotalAmountIDR)
76}
77
78// AC2: Stok tidak cukup
79func (s *PlaceOrderSuite) TestPlaceOrder_InsufficientStock_ReturnsErrInsufficientStock() {
80 s.productRepo.EXPECT().GetByID(gomock.Any(), s.productID.String()).
81 Return(s.mockProduct(2, 0), nil) // only 2 available
82
83 _, err := s.uc.Execute(context.Background(), s.validInput(5)) // request 5
84 s.ErrorIs(err, domainProduct.ErrInsufficientStock)
85}
86
87// AC3: Product tidak ditemukan
88func (s *PlaceOrderSuite) TestPlaceOrder_ProductNotFound_ReturnsErrProductNotFound() {
89 s.productRepo.EXPECT().GetByID(gomock.Any(), gomock.Any()).Return(nil, nil) // nil = not found
90
91 _, err := s.uc.Execute(context.Background(), s.validInput(1))
92 s.ErrorIs(err, domainProduct.ErrProductNotFound)
93}
94
95// AC5: Empty order
96func (s *PlaceOrderSuite) TestPlaceOrder_EmptyItems_ReturnsErrEmptyOrder() {
97 input := orderUC.PlaceOrderInput{UserID: s.userID, Items: nil}
98 _, err := s.uc.Execute(context.Background(), input)
99 s.ErrorIs(err, domainOrder.ErrEmptyOrder)
100}
101
102// Business rule: max 10 items
103func (s *PlaceOrderSuite) TestPlaceOrder_MaxItems_ReturnsErrMaxItemsExceeded() {
104 items := make([]orderUC.PlaceOrderItem, 11)
105 for i := range items { items[i] = orderUC.PlaceOrderItem{ProductID: uuid.New(), Quantity: 1} }
106 _, err := s.uc.Execute(context.Background(), orderUC.PlaceOrderInput{UserID: s.userID, Items: items})
107 s.ErrorIs(err, domainOrder.ErrMaxItemsExceeded)
108}
109
110// Price snapshot: harga terkunci saat order dibuat
111func (s *PlaceOrderSuite) TestPlaceOrder_PriceSnapshot_UsesProductPriceAtOrderTime() {
112 price := int64(150_000_00)
113 product := s.mockProduct(10, 0)
114 product.PriceIDR = price
115
116 s.productRepo.EXPECT().GetByID(gomock.Any(), s.productID.String()).Return(product, nil)
117 s.orderRepo.EXPECT().Create(gomock.Any(), gomock.AssignableToTypeOf(&domainOrder.Order{})).
118 DoAndReturn(func(_ context.Context, o *domainOrder.Order) error {
119 s.Equal(price, o.Items[0].UnitPriceIDR) // verify price snapshot
120 return nil
121 })
122 s.publisher.EXPECT().Publish(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
123
124 _, err := s.uc.Execute(context.Background(), s.validInput(2))
125 s.NoError(err)
126}
127
128func TestPlaceOrderSuite(t *testing.T) {
129 suite.Run(t, new(PlaceOrderSuite))
130}Perhatikan helper mockProduct dan validInput: keduanya memangkas boilerplate sehingga setiap test hanya fokus pada perbedaan skenario, bukan setup berulang.
16.04 Entity Tests: Zero Dependencies
Test dengan ROI tertinggi adalah entity test — tidak butuh mock apa pun karena domain layer bebas dependensi. Contoh berikut menguji aturan bisnis murni seperti window cancel dan validasi password.
1// internal/domain/order/entity_test.go
2// Tests yang bisa run tanpa mock apapun
3
4package order_test
5
6import (
7 "testing"
8 "time"
9
10 "github.com/stretchr/testify/assert"
11 domainOrder "github.com/santekno/santekno-shop/internal/domain/order"
12)
13
14func TestOrder_CanBeCancelled_PendingWithin30Min_ReturnsNil(t *testing.T) {
15 o := &domainOrder.Order{
16 Status: domainOrder.StatusPending,
17 CreatedAt: time.Now().Add(-10 * time.Minute),
18 }
19 assert.NoError(t, o.CanBeCancelled())
20}
21
22func TestOrder_CanBeCancelled_PendingOver30Min_ReturnsWindowExpired(t *testing.T) {
23 o := &domainOrder.Order{
24 Status: domainOrder.StatusPending,
25 CreatedAt: time.Now().Add(-31 * time.Minute),
26 }
27 assert.ErrorIs(t, o.CanBeCancelled(), domainOrder.ErrCancelWindowExpired)
28}
29
30func TestOrder_CanBeCancelled_Confirmed_ReturnsNotCancellable(t *testing.T) {
31 o := &domainOrder.Order{Status: domainOrder.StatusConfirmed, CreatedAt: time.Now()}
32 assert.ErrorIs(t, o.CanBeCancelled(), domainOrder.ErrOrderNotCancellable)
33}
34
35func TestOrder_CalculateTotal_MultipleItems_CorrectTotal(t *testing.T) {
36 o := &domainOrder.Order{
37 Items: []domainOrder.OrderItem{
38 {UnitPriceIDR: 100_000_00, Quantity: 2}, // subtotal: 200_000_00
39 {UnitPriceIDR: 50_000_00, Quantity: 3}, // subtotal: 150_000_00
40 },
41 }
42 o.CalculateTotal()
43 assert.Equal(t, int64(350_000_00), o.TotalAmountIDR)
44}
45
46func TestProduct_AvailableStock_ReturnsStockMinusReserved(t *testing.T) {
47 p := &domainOrder.Product{Stock: 10, ReservedStock: 3}
48 assert.Equal(t, 7, p.AvailableStock())
49}
50
51func TestValidatePassword_TooShort_ReturnsWeakPassword(t *testing.T) {
52 err := domainUser.ValidatePassword("short1")
53 assert.ErrorIs(t, err, domainUser.ErrWeakPassword)
54}
55
56func TestValidatePassword_NoDigit_ReturnsWeakPassword(t *testing.T) {
57 err := domainUser.ValidatePassword("LongButNoDigit")
58 assert.ErrorIs(t, err, domainUser.ErrWeakPassword)
59}
60
61func TestValidatePassword_Valid_ReturnsNil(t *testing.T) {
62 err := domainUser.ValidatePassword("Secret123")
63 assert.NoError(t, err)
64}Karena berjalan dalam milidetik tanpa setup, entity test seperti ini adalah tempat pertama untuk mengunci aturan bisnis — dan yang paling murah untuk dijalankan berulang.
16.05 Mock Generation Setup
Agar unit test tidak menyentuh DB atau Kafka sungguhan, setiap interface repository diberi directive go:generate untuk mockgen. Blok berikut menunjukkan pola directive dan struktur folder hasilnya.
1// Setiap repository interface punya go:generate directive
2
3// internal/domain/user/repository.go
4//go:generate mockgen -destination=../../../testutil/mock/user_repo_mock.go \
5// -package=mock -source=repository.go
6
7// internal/domain/order/repository.go
8//go:generate mockgen -destination=../../../testutil/mock/order_repo_mock.go \
9// -package=mock -source=repository.go
10
11// internal/domain/product/repository.go
12//go:generate mockgen -destination=../../../testutil/mock/product_repo_mock.go \
13// -package=mock -source=repository.go
14
15// internal/domain/payment/repository.go
16//go:generate mockgen -destination=../../../testutil/mock/payment_repo_mock.go \
17// -package=mock -source=repository.go
18
19// internal/event/publisher.go
20//go:generate mockgen -destination=../../testutil/mock/event_publisher_mock.go \
21// -package=mock -source=publisher.go
22
23// Jalankan semua:
24go generate ./...
25
26// Struktur testutil/mock/:
27// testutil/mock/
28// user_repo_mock.go
29// order_repo_mock.go
30// product_repo_mock.go
31// payment_repo_mock.go
32// event_publisher_mock.go
33// email_sender_mock.go
34// rate_limiter_mock.goDengan directive yang menempel di file interface, satu perintah go generate ./... cukup untuk menyegarkan semua mock — dan CI bisa memverifikasi mock tetap sinkron (kita bahas di Artikel 17).
16.06 Integration Test Setup
Integration test butuh koneksi PostgreSQL sungguhan plus mekanisme reset antar test. Helper Setup dan TruncateAll berikut menyediakan pool koneksi dan membersihkan state di awal setiap test.
1// testutil/testdb/setup.go
2
3package testdb
4
5import (
6 "context"
7 "fmt"
8 "os"
9 "testing"
10 "time"
11
12 "github.com/jackc/pgx/v5/pgxpool"
13 "github.com/stretchr/testify/require"
14)
15
16// Setup: connect to test DB + ensure fresh schema
17func Setup(t *testing.T) *pgxpool.Pool {
18 t.Helper()
19
20 dbURL := os.Getenv("TEST_DATABASE_URL")
21 if dbURL == "" {
22 dbURL = "postgres://santekno:secret@localhost:5432/santekno_test?sslmode=disable"
23 }
24
25 pool, err := pgxpool.New(context.Background(), dbURL)
26 require.NoError(t, err, "failed to connect to test DB")
27
28 // Ping check
29 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
30 defer cancel()
31 require.NoError(t, pool.Ping(ctx), "test DB not reachable")
32
33 t.Cleanup(func() {
34 pool.Close()
35 })
36
37 return pool
38}
39
40// TruncateAll: reset semua tabel sebelum test (lebih cepat dari DROP/CREATE)
41func TruncateAll(t *testing.T, pool *pgxpool.Pool) {
42 t.Helper()
43 ctx := context.Background()
44 _, err := pool.Exec(ctx, `
45 TRUNCATE TABLE
46 notifications, outbox_events, payments,
47 order_items, orders, refresh_tokens,
48 users, products, categories
49 RESTART IDENTITY CASCADE
50 `)
51 require.NoError(t, err)
52}Kunci di sini adalah TruncateAll yang dipanggil di awal (bukan akhir) tiap test — jauh lebih cepat dari drop/create schema dan menjamin isolasi antar test tanpa saling mencemari.
16.07 Integration Test: OrderRepository
Repository adalah layer yang paling butuh DB sungguhan karena menguji transaksi atomik dan query SQL. Suite berikut memverifikasi reserve stock, rollback saat stok kurang, dan restore stock saat cancel.
1// internal/repository/postgres/order_repository_integration_test.go
2//go:build integration
3
4package postgres_test
5
6import (
7 "context"
8 "testing"
9 "time"
10
11 "github.com/google/uuid"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14 "github.com/stretchr/testify/suite"
15
16 domainOrder "github.com/santekno/santekno-shop/internal/domain/order"
17 postgres "github.com/santekno/santekno-shop/internal/repository/postgres"
18 "github.com/santekno/santekno-shop/testutil/testdb"
19)
20
21type OrderRepositoryIntegrationSuite struct {
22 suite.Suite
23 pool *testdb.Pool
24 repo *postgres.OrderRepository
25 productID string
26 userID string
27}
28
29func (s *OrderRepositoryIntegrationSuite) SetupSuite() {
30 s.pool = testdb.Setup(s.T())
31 s.repo = postgres.NewOrderRepository(s.pool)
32}
33
34func (s *OrderRepositoryIntegrationSuite) SetupTest() {
35 testdb.TruncateAll(s.T(), s.pool)
36
37 // Seed user
38 s.pool.QueryRow(context.Background(),
39 `INSERT INTO users (email, password_hash, name, is_active) VALUES ($1,$2,$3,$4) RETURNING id`,
40 "test@order.com", "hash", "Test User", true,
41 ).Scan(&s.userID)
42
43 // Seed product with stock 10
44 s.pool.QueryRow(context.Background(),
45 `INSERT INTO products (name, price_idr, stock, is_active) VALUES ($1,$2,$3,$4) RETURNING id`,
46 "Test Product", 100_000_00, 10, true,
47 ).Scan(&s.productID)
48}
49
50// Test: Create order dan verify stock reserved secara atomic
51func (s *OrderRepositoryIntegrationSuite) TestCreate_AtomicStockReserve() {
52 ctx := context.Background()
53 uid, _ := uuid.Parse(s.userID)
54 pid, _ := uuid.Parse(s.productID)
55
56 order := &domainOrder.Order{
57 ID: uuid.New(),
58 UserID: uid,
59 Status: domainOrder.StatusPending,
60 Items: []domainOrder.OrderItem{{
61 ID: uuid.New(), ProductID: pid,
62 ProductName: "Test", UnitPriceIDR: 100_000_00, Quantity: 3,
63 }},
64 TotalAmountIDR: 300_000_00,
65 PaymentMethod: domainOrder.PaymentQRIS,
66 CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
67 }
68
69 err := s.repo.Create(ctx, order)
70 require.NoError(s.T(), err)
71
72 // Verify reserved_stock incremented
73 var reserved int
74 s.pool.QueryRow(ctx, "SELECT reserved_stock FROM products WHERE id = $1", s.productID).Scan(&reserved)
75 assert.Equal(s.T(), 3, reserved)
76
77 // Verify outbox event created
78 var outboxCount int
79 s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM outbox_events WHERE published = false").Scan(&outboxCount)
80 assert.GreaterOrEqual(s.T(), outboxCount, 1)
81}
82
83// Test: Create order dengan stok tidak cukup → rollback
84func (s *OrderRepositoryIntegrationSuite) TestCreate_InsufficientStock_RollsBack() {
85 ctx := context.Background()
86 uid, _ := uuid.Parse(s.userID)
87 pid, _ := uuid.Parse(s.productID)
88
89 order := &domainOrder.Order{
90 ID: uuid.New(),
91 UserID: uid,
92 Status: domainOrder.StatusPending,
93 Items: []domainOrder.OrderItem{{
94 ID: uuid.New(), ProductID: pid,
95 ProductName: "Test", UnitPriceIDR: 100_000_00, Quantity: 15, // lebih dari stock 10
96 }},
97 TotalAmountIDR: 1_500_000_00,
98 PaymentMethod: domainOrder.PaymentQRIS,
99 CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
100 }
101
102 err := s.repo.Create(ctx, order)
103 assert.Error(s.T(), err)
104 assert.ErrorIs(s.T(), err, domainProduct.ErrInsufficientStock)
105
106 // Verify: order NOT created (rollback worked)
107 var orderCount int
108 s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM orders WHERE id = $1", order.ID).Scan(&orderCount)
109 assert.Equal(s.T(), 0, orderCount)
110
111 // Verify: reserved_stock NOT changed
112 var reserved int
113 s.pool.QueryRow(ctx, "SELECT reserved_stock FROM products WHERE id = $1", s.productID).Scan(&reserved)
114 assert.Equal(s.T(), 0, reserved)
115}
116
117// Test: Cancel order → restore stock
118func (s *OrderRepositoryIntegrationSuite) TestCancel_RestoresStock() {
119 ctx := context.Background()
120 uid, _ := uuid.Parse(s.userID)
121 pid, _ := uuid.Parse(s.productID)
122 orderID := uuid.New()
123
124 // Create order directly in DB (not via repo to isolate)
125 s.pool.Exec(ctx, `INSERT INTO orders (id, user_id, status, total_amount_idr, payment_method, shipping_address, created_at, updated_at)
126 VALUES ($1,$2,'PENDING',300000,'QRIS','{}', NOW(), NOW())`, orderID, uid)
127 s.pool.Exec(ctx, `INSERT INTO order_items (order_id, product_id, product_name, unit_price_idr, quantity, subtotal_idr)
128 VALUES ($1,$2,'Test',100000,3,300000)`, orderID, pid)
129 s.pool.Exec(ctx, `UPDATE products SET reserved_stock = 3 WHERE id = $1`, pid)
130
131 err := s.repo.Cancel(ctx, orderID)
132 require.NoError(s.T(), err)
133
134 // Verify order status
135 var status string
136 s.pool.QueryRow(ctx, "SELECT status FROM orders WHERE id = $1", orderID).Scan(&status)
137 assert.Equal(s.T(), "CANCELLED", status)
138
139 // Verify stock restored
140 var reserved int
141 s.pool.QueryRow(ctx, "SELECT reserved_stock FROM products WHERE id = $1", s.productID).Scan(&reserved)
142 assert.Equal(s.T(), 0, reserved)
143}
144
145func TestOrderRepositoryIntegrationSuite(t *testing.T) {
146 if testing.Short() { t.Skip("skipping integration test") }
147 suite.Run(t, new(OrderRepositoryIntegrationSuite))
148}Test seperti TestCreate_InsufficientStock_RollsBack membuktikan properti yang mustahil diverifikasi dengan mock: bahwa transaksi benar-benar rollback di level database, bukan hanya di logika Go.
16.08 E2E Test Setup dengan Prism
E2E test butuh server yang merespons request HTTP nyata. Perintah berikut menjalankan Prism sebagai mock server yang memvalidasi request/response terhadap OpenAPI spec.
1# E2E test menggunakan Prism sebagai mock server
2# Validate request/response against OpenAPI spec
3
4# Jalankan Prism mock server:
5docker run --rm -p 4010:4010 \
6 -v $(pwd)/api/openapi.yaml:/api/openapi.yaml \
7 stoplight/prism:4 mock /api/openapi.yaml
8
9# Atau jalankan real server untuk E2E:
10# docker-compose -f docker-compose.test.yml up -d
11# go test -tags=e2e ./test/e2e/...Dengan Prism, kamu bisa menjalankan E2E test lebih awal — bahkan sebelum implementasi backend selesai — karena kontrak OpenAPI sudah cukup untuk memvalidasi bentuk request dan response.
16.09 E2E Test: Register dan Login Flow
E2E test yang paling berharga menguji satu perjalanan user utuh dalam satu fungsi. Test berikut merangkai register → login → place order → cancel lewat HTTP sungguhan.
1// test/e2e/auth_flow_test.go
2//go:build e2e
3
4package e2e_test
5
6import (
7 "bytes"
8 "encoding/json"
9 "fmt"
10 "net/http"
11 "os"
12 "testing"
13
14 "github.com/stretchr/testify/assert"
15 "github.com/stretchr/testify/require"
16)
17
18var baseURL = func() string {
19 if u := os.Getenv("E2E_BASE_URL"); u != "" { return u }
20 return "http://localhost:8080"
21}()
22
23func post(t *testing.T, path string, body interface{}, token string) *http.Response {
24 t.Helper()
25 b, _ := json.Marshal(body)
26 req, _ := http.NewRequest(http.MethodPost, baseURL+path, bytes.NewReader(b))
27 req.Header.Set("Content-Type", "application/json")
28 if token != "" {
29 req.Header.Set("Authorization", "Bearer "+token)
30 }
31 resp, err := http.DefaultClient.Do(req)
32 require.NoError(t, err)
33 return resp
34}
35
36// E2E: Full register → login → place order → cancel flow
37func TestE2E_RegisterLoginPlaceOrderCancel(t *testing.T) {
38 // Step 1: Register
39 regResp := post(t, "/api/v1/auth/register", map[string]string{
40 "email": fmt.Sprintf("e2e-%d@test.com", os.Getpid()),
41 "password": "E2Epassword1",
42 "name": "E2E Test User",
43 }, "")
44 assert.Equal(t, http.StatusCreated, regResp.StatusCode, "register failed")
45
46 // Step 2: Login
47 loginResp := post(t, "/api/v1/auth/login", map[string]string{
48 "email": fmt.Sprintf("e2e-%d@test.com", os.Getpid()),
49 "password": "E2Epassword1",
50 }, "")
51 assert.Equal(t, http.StatusOK, loginResp.StatusCode, "login failed")
52
53 var loginBody struct {
54 AccessToken string `json:"access_token"`
55 }
56 json.NewDecoder(loginResp.Body).Decode(&loginBody)
57 require.NotEmpty(t, loginBody.AccessToken, "no access token")
58
59 token := loginBody.AccessToken
60
61 // Step 3: Get product ID
62 prodResp, _ := http.Get(baseURL + "/api/v1/products?limit=1")
63 var prodBody struct {
64 Data []struct { ID string `json:"id"` } `json:"data"`
65 }
66 json.NewDecoder(prodResp.Body).Decode(&prodBody)
67 require.NotEmpty(t, prodBody.Data, "no products found")
68 productID := prodBody.Data[0].ID
69
70 // Step 4: Place order
71 orderResp := post(t, "/api/v1/orders", map[string]interface{}{
72 "items": []map[string]interface{}{{"product_id": productID, "quantity": 1}},
73 "shipping_address_id": "00000000-0000-0000-0000-000000000001",
74 "payment_method": "QRIS",
75 }, token)
76 assert.Equal(t, http.StatusCreated, orderResp.StatusCode, "place order failed")
77
78 var orderBody struct {
79 ID string `json:"id"`
80 }
81 json.NewDecoder(orderResp.Body).Decode(&orderBody)
82 require.NotEmpty(t, orderBody.ID, "no order ID")
83
84 // Step 5: Cancel order (within 30 min window)
85 req, _ := http.NewRequest(http.MethodDelete,
86 baseURL+"/api/v1/orders/"+orderBody.ID, nil)
87 req.Header.Set("Authorization", "Bearer "+token)
88 cancelResp, _ := http.DefaultClient.Do(req)
89 assert.Equal(t, http.StatusNoContent, cancelResp.StatusCode, "cancel failed")
90}Satu test ini sekaligus memvalidasi JWT middleware, auth flow, reservasi stok, dan aturan cancel — persis apa yang dialami user nyata, dalam urutan yang benar.
16.10 Coverage Target per Layer
Coverage bukan angka tunggal — tiap layer punya target berbeda sesuai risikonya. Tabel target berikut jadi acuan sekaligus gate di CI.
1TARGET COVERAGE:
2
3Domain entities:
4 target: 90%+
5 rationale: business rules harus fully tested, no dependencies
6
7UseCase layer:
8 target: 85%+
9 rationale: semua AC dari spec harus ada test-nya
10
11Repository layer:
12 target: 70%+ (integration tests)
13 rationale: SQL queries butuh real DB untuk meaningful test
14
15Handler layer:
16 target: 60%+
17 rationale: thin layer, mostly wiring — tested via E2E
18
19Overall:
20 target: 75%+ (combined unit + integration)
21 CI gate: FAIL if < 70% overall
22
23Run coverage:
24 go test -cover ./internal/domain/...
25 go test -cover ./internal/usecase/...
26 go test -tags=integration -cover ./internal/repository/...Target yang lebih tinggi di domain dan usecase mencerminkan prinsip: semakin dekat kode ke aturan bisnis, semakin ketat cakupan test yang kita tuntut.
16.11 Test Tags Strategy
Agar layer test bisa dijalankan terpisah, kita pakai build tag Go. Ringkasan berikut memetakan tiap tag ke kebutuhan dependensinya dan perintah menjalankannya.
1// Build tags untuk isolasi test layer:
2
3// Unit tests: tidak perlu tag (default)
4// go test ./...
5
6// Integration tests: butuh test DB
7//go:build integration
8// go test -tags=integration ./...
9
10// E2E tests: butuh running server
11//go:build e2e
12// go test -tags=e2e ./test/e2e/...
13
14// Benchmarks: untuk performance profiling
15//go:build bench
16// go test -tags=bench -bench=. ./...
17
18// CI pipeline:
19// make test-unit → default (fast, no external deps)
20// make test-integration → spin up Docker, run integration
21// make test-e2e → full stack, run e2eDengan pembagian tag ini, developer bisa menjalankan unit test secepat kilat di laptop, sementara integration dan E2E hanya dipicu saat dependensi tersedia (lokal atau CI).
16.12 Makefile Test Commands
Perintah test yang panjang sebaiknya dibungkus di Makefile agar konsisten antara lokal dan CI. Target-target berikut memisahkan unit, integration, E2E, dan coverage.
1# Makefile
2
3.PHONY: test test-unit test-integration test-e2e test-cover
4
5# Unit tests (default — fast)
6test-unit:
7 go test -race -count=1 ./internal/domain/... ./internal/usecase/... ./pkg/...
8
9# Integration tests (requires: PostgreSQL + Redis running)
10test-integration:
11 go test -race -tags=integration -count=1 ./internal/repository/... \
12 -v -timeout=60s
13
14# E2E tests (requires: full stack)
15test-e2e:
16 go test -tags=e2e -count=1 ./test/e2e/... -v -timeout=120s
17
18# All tests with coverage report
19test-cover:
20 go test -race -coverprofile=coverage.out -covermode=atomic \
21 ./internal/domain/... ./internal/usecase/... ./pkg/...
22 go tool cover -html=coverage.out -o coverage.html
23 go tool cover -func=coverage.out | grep total
24
25# Run all (unit + integration)
26test: test-unit test-integrationKarena target ini dipakai persis sama di CI, “works on my machine” jadi jauh lebih sulit terjadi — perintah yang gagal lokal juga akan gagal di pipeline.
16.13 Spec AC Traceability Matrix
Inti dari SDD adalah setiap AC bisa ditelusuri ke test-nya. Matriks traceability berikut memetakan tiap fitur, AC, test function, dan layernya.
1Spec Feature | AC | Test Function | Layer
2-------------------|----|--------------------------------------------|---------
3user-registration | 1 | TestRegisterUser_ValidInput_Creates201 | unit
4 | 2 | TestRegisterUser_EmailExists_Returns409 | unit
5 | 3 | TestRegisterUser_WeakPassword_Returns400 | unit
6 | 4 | TestRegisterUser_InvalidEmail_Returns400 | unit
7user-login | 1 | TestLoginUser_ValidCreds_ReturnsTokens | unit
8 | 2 | TestLoginUser_EmailNotFound_Returns401 | unit
9 | 3 | TestLoginUser_WrongPassword_Returns401 | unit
10 | 4 | TestLoginUser_RateLimited_Returns429 | unit
11product-catalog | 1 | TestListProducts_ValidFilter_ReturnsList | unit
12 | 2 | TestListProducts_WithQuery_SearchWorks | integration
13 | 3 | TestGetProduct_NotFound_Returns404 | unit
14 | 4 | TestGetProduct_Inactive_ReturnsWithStock0 | unit
15place-order | 1 | TestPlaceOrder_ValidItems_Creates201 | unit + integration
16 | 2 | TestPlaceOrder_InsufficientStock_Returns422 | unit + integration
17 | 3 | TestPlaceOrder_ProductNotFound_Returns404 | unit
18 | 4 | (JWT middleware test) | unit
19 | 5 | TestPlaceOrder_EmptyItems_Returns400 | unit
20cancel-order | 1 | TestCancelOrder_PendingWithin30Min_204 | unit + integration
21 | 2 | TestCancelOrder_Confirmed_Returns409 | unit
22 | 3 | TestCancelOrder_WindowExpired_Returns409 | unit
23 | 4 | TestCancelOrder_NotFound_Returns404 | unit
24get-orders | 1 | TestGetOrders_ValidInput_ReturnsList | unit
25 | 2 | TestGetOrders_FilterByStatus | unit
26 | 3 | TestGetOrders_DefaultPagination | unit
27 | 4 | TestGetOrders_ScopedToUser | unit
28payment-webhook | 1 | TestWebhook_Paid_ConfirmsOrder | unit + integration
29 | 2 | TestWebhook_Failed_CancelsOrder | unit + integration
30 | 3 | TestWebhook_InvalidSignature_Returns401 | unit
31 | 4 | TestWebhook_Duplicate_Idempotent200 | unit + integrationMatriks inilah yang nantinya dibaca oleh specify audit untuk menghitung skor spec compliance — sebuah AC tanpa baris di sini berarti fitur yang belum terbukti bekerja.
16.14 Table-Driven Tests untuk Error Scenarios
Ketika banyak skenario mirip hanya berbeda input, table-driven test jauh lebih ringkas dari menulis fungsi terpisah. Contoh berikut menguji beragam variasi validasi password dalam satu tabel.
1// Untuk banyak error scenarios yang mirip — gunakan table-driven
2
3func TestRegisterUser_PasswordValidation(t *testing.T) {
4 tests := []struct {
5 name string
6 password string
7 wantErr error
8 }{
9 {"too short", "Sh1", domainUser.ErrWeakPassword},
10 {"no digit", "NoDigitInPass", domainUser.ErrWeakPassword},
11 {"exactly 8 chars", "Secret1!", nil},
12 {"long password", "VeryLongP4ss!", nil},
13 {"only digits", "12345678", nil},
14 {"unicode with digit", "Räksmörgås1", nil},
15 }
16
17 for _, tc := range tests {
18 t.Run(tc.name, func(t *testing.T) {
19 err := domainUser.ValidatePassword(tc.password)
20 if tc.wantErr != nil {
21 assert.ErrorIs(t, err, tc.wantErr)
22 } else {
23 assert.NoError(t, err)
24 }
25 })
26 }
27}Setiap baris punya name sehingga saat satu case gagal, output test langsung menunjuk skenario mana yang bermasalah tanpa perlu menebak.
16.15 Test Redis Rate Limiter
Rate limiter berbasis Redis butuh instance Redis nyata untuk diuji dengan benar. Helper setup berikut menyiapkan client Redis test yang otomatis di-flush setelah selesai.
1// testutil/testredis/setup.go
2
3package testredis
4
5import (
6 "context"
7 "os"
8 "testing"
9
10 "github.com/redis/go-redis/v9"
11 "github.com/stretchr/testify/require"
12)
13
14func Setup(t *testing.T) *redis.Client {
15 t.Helper()
16 addr := os.Getenv("TEST_REDIS_ADDR")
17 if addr == "" { addr = "localhost:6379" }
18
19 client := redis.NewClient(&redis.Options{Addr: addr, DB: 1}) // DB 1 = test DB
20 require.NoError(t, client.Ping(context.Background()).Err())
21
22 t.Cleanup(func() {
23 client.FlushDB(context.Background()) // clean after test
24 client.Close()
25 })
26 return client
27}Perhatikan pemakaian DB: 1 sebagai database test terpisah — ini mencegah FlushDB di test menghapus data development yang biasanya ada di DB 0.
Setelah setup siap, test rate limiter berikut memverifikasi bahwa call ke-6 ditolak setelah 5 call pertama lolos.
1// internal/infrastructure/redis/rate_limiter_integration_test.go
2//go:build integration
3
4func TestRateLimiter_Allow_ExceedsMax_ReturnsFalse(t *testing.T) {
5 rdb := testredis.Setup(t)
6 rl := redisinfra.NewRateLimiter(rdb)
7 ctx := context.Background()
8 key := "test:ratelimit"
9
10 // 5 calls should pass
11 for i := 0; i < 5; i++ {
12 allowed, err := rl.Allow(ctx, key, 5, 60)
13 assert.NoError(t, err)
14 assert.True(t, allowed)
15 }
16
17 // 6th call should fail
18 allowed, err := rl.Allow(ctx, key, 5, 60)
19 assert.NoError(t, err)
20 assert.False(t, allowed)
21}Test ini mengunci AC “rate limit → 429” di level infrastruktur, memastikan window dan counter benar-benar bekerja di Redis, bukan sekadar diasumsikan di logika usecase.
16.16 Handler Test dengan httptest
Handler bisa diuji terisolasi memakai httptest tanpa menjalankan server penuh. Contoh berikut memverifikasi handler register mengembalikan status 201 dengan usecase yang di-mock.
1// delivery/http/handler/auth_handler_test.go
2
3package handler_test
4
5import (
6 "bytes"
7 "encoding/json"
8 "net/http"
9 "net/http/httptest"
10 "testing"
11
12 "github.com/labstack/echo/v4"
13 "github.com/stretchr/testify/assert"
14 "go.uber.org/mock/gomock"
15)
16
17func TestAuthHandler_Register_ValidRequest_Returns201(t *testing.T) {
18 ctrl := gomock.NewController(t)
19 defer ctrl.Finish()
20
21 // Setup mock usecase
22 registerUC := mock.NewMockRegisterUserUseCase(ctrl)
23 registerUC.EXPECT().Execute(gomock.Any(), gomock.Any()).Return(&auth.RegisterOutput{
24 ID: uuid.New(), Email: "user@test.com", Name: "Test",
25 }, nil)
26
27 h := handler.NewAuthHandler(registerUC, nil)
28
29 // Build request
30 body, _ := json.Marshal(map[string]string{
31 "email": "user@test.com", "password": "Secret123", "name": "Test",
32 })
33 req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", bytes.NewReader(body))
34 req.Header.Set("Content-Type", "application/json")
35 rec := httptest.NewRecorder()
36
37 e := echo.New()
38 c := e.NewContext(req, rec)
39
40 err := h.Register(c)
41 assert.NoError(t, err)
42 assert.Equal(t, http.StatusCreated, rec.Code)
43}Handler test fokus pada parsing request, validasi, dan format response — sedangkan logika bisnisnya sudah diuji terpisah di unit test usecase, jadi tidak ada duplikasi cakupan.
16.17 CI Test Pipeline Configuration
Semua layer test harus berjalan otomatis di CI dengan dependensi yang tepat. Konfigurasi GitHub Actions berikut menjalankan unit test dengan coverage gate, lalu integration test dengan PostgreSQL dan Redis.
1# .github/workflows/test.yml (bagian testing)
2
3jobs:
4 unit-test:
5 runs-on: ubuntu-latest
6 steps:
7 - uses: actions/checkout@v4
8 - uses: actions/setup-go@v5
9 with: { go-version: '1.22' }
10 - name: Run unit tests
11 run: |
12 go test -race -count=1 -timeout=60s \
13 -coverprofile=unit-coverage.out \
14 ./internal/domain/... ./internal/usecase/... ./pkg/...
15 - name: Check coverage
16 run: |
17 COVERAGE=$(go tool cover -func=unit-coverage.out | grep total | awk '{print $3}' | sed 's/%//')
18 if (( $(echo "$COVERAGE < 80" | bc -l) )); then
19 echo "Coverage $COVERAGE% is below 80%"
20 exit 1
21 fi
22
23 integration-test:
24 runs-on: ubuntu-latest
25 services:
26 postgres:
27 image: postgres:15
28 env:
29 POSTGRES_DB: santekno_test
30 POSTGRES_USER: santekno
31 POSTGRES_PASSWORD: secret
32 options: --health-cmd pg_isready --health-interval 10s
33 redis:
34 image: redis:7-alpine
35 options: --health-cmd "redis-cli ping"
36 steps:
37 - uses: actions/checkout@v4
38 - uses: actions/setup-go@v5
39 with: { go-version: '1.22' }
40 - name: Run migrations on test DB
41 run: |
42 go install github.com/golang-migrate/migrate/v4/cmd/migrate@latest
43 migrate -path migrations -database "$TEST_DATABASE_URL" up
44 env:
45 TEST_DATABASE_URL: postgres://santekno:secret@localhost:5432/santekno_test
46 - name: Run integration tests
47 run: go test -tags=integration -race -timeout=120s ./internal/repository/...
48 env:
49 TEST_DATABASE_URL: postgres://santekno:secret@localhost:5432/santekno_test
50 TEST_REDIS_ADDR: localhost:6379GitHub Actions services men-spin up container PostgreSQL dan Redis segar untuk tiap run, sehingga integration test selalu berjalan di atas state bersih tanpa kontaminasi antar build.
16.18 Race Condition Detection
Bug konkuren adalah kelas bug paling berbahaya karena sering lolos review. Flag -race dan skenario concurrent berikut adalah cara kita menangkapnya sebelum sampai production.
1# Selalu jalankan test dengan -race flag
2go test -race ./...
3
4# Common race conditions yang harus di-test:
5# 1. Concurrent PlaceOrder (stock reservation)
6# 2. Concurrent refresh token rotation
7# 3. Outbox worker + concurrent order creation
8
9# Test concurrent place order:
10# func TestPlaceOrder_ConcurrentRequests_NoOverselling(t *testing.T) {
11# // Setup: product dengan stock 5
12# // Launch: 10 goroutines place order qty 1 secara bersamaan
13# // Expect: 5 success, 5 ErrInsufficientStock
14# // Verify: reserved_stock == 5 (tidak lebih)
15# // Implementasi: integration test dengan real DB + goroutines
16# // go test -race -tags=integration -run TestPlaceOrder_Concurrent
17# }Skenario overselling adalah ujian nyata: 10 goroutine berebut 5 unit terakhir harus menghasilkan tepat 5 sukses dan 5 gagal — dan -race memastikan tidak ada akses memori tak tersinkron di sepanjang jalannya.
16.19 Test Data Management
Setup data test yang berulang sebaiknya dibungkus dalam builder agar test tetap ringkas. Package fixtures berikut menyediakan konstruktor reusable untuk user, product, dan order.
1// testutil/fixtures/fixtures.go
2// Reusable test data builders
3
4package fixtures
5
6import (
7 "fmt"
8 "time"
9 "github.com/google/uuid"
10 domainOrder "github.com/santekno/santekno-shop/internal/domain/order"
11 domainProduct "github.com/santekno/santekno-shop/internal/domain/product"
12 domainUser "github.com/santekno/santekno-shop/internal/domain/user"
13)
14
15// User fixtures
16func NewUser() *domainUser.User {
17 return &domainUser.User{
18 ID: uuid.New(),
19 Email: fmt.Sprintf("test-%s@example.com", uuid.New().String()[:8]),
20 PasswordHash: "$2a$12$test_hash",
21 Name: "Test User",
22 IsActive: true,
23 CreatedAt: time.Now().UTC(),
24 }
25}
26
27// Product fixtures
28func NewProduct(stock int) *domainProduct.Product {
29 return &domainProduct.Product{
30 ID: uuid.New(),
31 Name: "Test Product",
32 PriceIDR: 100_000_00,
33 Stock: stock,
34 IsActive: true,
35 }
36}
37
38// Order fixtures
39func NewPendingOrder(userID, productID uuid.UUID, qty int) *domainOrder.Order {
40 price := int64(100_000_00)
41 return &domainOrder.Order{
42 ID: uuid.New(),
43 UserID: userID,
44 Status: domainOrder.StatusPending,
45 Items: []domainOrder.OrderItem{{
46 ID: uuid.New(), ProductID: productID,
47 ProductName: "Test", UnitPriceIDR: price,
48 Quantity: qty, SubtotalIDR: price * int64(qty),
49 }},
50 TotalAmountIDR: price * int64(qty),
51 PaymentMethod: domainOrder.PaymentQRIS,
52 CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
53 }
54}Konstruktor seperti NewUser menghasilkan email unik lewat UUID, sehingga test yang berjalan paralel tidak saling bentrok karena data duplikat.
16.20 Ringkasan: Testing Strategy Santekno Shop
Testing di Santekno Shop mengikuti satu prinsip: setiap AC dari spec harus memiliki minimal satu test yang mengkovernya. Tiga layer bekerja bersama untuk itu.
Unit tests (150+ test cases): cepat, terisolasi, mengkover semua usecase dan entity domain. Mock digenerate dari interface.
Integration tests (50+ test cases): real PostgreSQL + Redis, memverifikasi transaksi atomik, query SQL, dan race condition.
E2E tests (20 test cases): happy path via HTTP, full stack, dengan opsi Prism mock server.
CI gates: unit coverage ≥ 80%, specify audit ≥ 80, lint bersih, dan bebas race condition. Traceability matrix menjamin 29 AC dari spec ter-cover, sementara konvensi penamaan membuat setiap kegagalan mudah ditelusuri balik ke spec-nya.