Golang Testing Strategy: Unit, Integration, and E2E Tests from Spec
The complete testing strategy for Santekno Shop. Unit tests with testify + gomock, integration tests against real PostgreSQL, and E2E tests with the Prism mock server — all derived from spec ACs.
A good golang testing strategy is not an afterthought — in Santekno Shop, every acceptance criterion (AC) from the spec has a test that covers it. We already wrote most of these tests in Articles 06-10, but in this article we formalize the strategy: directory structure, test harness, and how to run each layer separately so it stays traceable back to the spec.
16.01 The Santekno Shop Testing Pyramid
Before writing a single test, we need a map of proportions: how many tests live in each layer and how fast they run. The pyramid diagram below summarizes the split in 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 endThe principle: the majority of tests live in the fast unit layer, and only a handful of expensive E2E tests exist — so the feedback loop stays lightning-fast without sacrificing coverage.
16.02 Test Naming Convention from Spec
A good test name immediately tells you which AC it covers without opening the spec. The naming pattern below makes every test function traceable to its acceptance criteria.
1// Format: Test[UseCase]_[Scenario]_[ExpectedResult]
2// Directly traceable to the Spec AC
3
4// From spec: place-order AC2 "insufficient stock → 422"
5func (s *PlaceOrderSuite) TestPlaceOrder_InsufficientStock_Returns422() { ... }
6
7// From spec: cancel-order AC3 "window expired → 409"
8func (s *CancelOrderSuite) TestCancelOrder_WindowExpired_Returns409() { ... }
9
10// From 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]With this convention, when a test fails you immediately know which AC regressed — not just that “there’s a red test.”
16.03 Test Suite Structure with testify/suite
To group tests for a single usecase and share setup, we use testify/suite. The structure below prepares fresh mocks for each test via SetupTest and verifies expectations in 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: all tests for the PlaceOrder usecase in one 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: Successfully create an 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: Insufficient stock
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 not found
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: price locked at order creation time
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}Notice the mockProduct and validInput helpers: both trim boilerplate so each test focuses only on what differs across scenarios, not repeated setup.
16.04 Entity Tests: Zero Dependencies
The tests with the highest ROI are entity tests — they need no mocks at all because the domain layer is dependency-free. The example below exercises pure business rules like the cancel window and password validation.
1// internal/domain/order/entity_test.go
2// Tests that can run without any mocks
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}Because they run in milliseconds with no setup, entity tests like these are the first place to lock down business rules — and the cheapest to run repeatedly.
16.05 Mock Generation Setup
So that unit tests never touch a real DB or Kafka, every repository interface gets a go:generate directive for mockgen. The block below shows the directive pattern and the resulting folder structure.
1// Every repository interface has a 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// Run all:
24go generate ./...
25
26// testutil/mock/ structure:
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.goWith the directive attached to each interface file, a single go generate ./... refreshes all mocks — and CI can verify the mocks stay in sync (we cover this in Article 17).
16.06 Integration Test Setup
Integration tests need a real PostgreSQL connection plus a mechanism to reset state between tests. The Setup and TruncateAll helpers below provide a connection pool and clean state at the start of each 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 all tables before the test (faster than 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}The key here is TruncateAll, called at the start (not the end) of each test — far faster than dropping/creating the schema, and it guarantees isolation between tests without cross-contamination.
16.07 Integration Test: OrderRepository
The repository is the layer that most needs a real DB because it exercises atomic transactions and SQL queries. The suite below verifies stock reservation, rollback on insufficient stock, and stock restoration on 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 and verify stock is reserved atomically
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 with insufficient stock → 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, // more than 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}A test like TestCreate_InsufficientStock_RollsBack proves a property that is impossible to verify with mocks: that the transaction truly rolls back at the database level, not just in the Go logic.
16.08 E2E Test Setup with Prism
E2E tests need a server that responds to real HTTP requests. The command below runs Prism as a mock server that validates requests and responses against the OpenAPI spec.
1# E2E tests use Prism as the mock server
2# Validate request/response against the OpenAPI spec
3
4# Run the 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# Or run the real server for E2E:
10# docker-compose -f docker-compose.test.yml up -d
11# go test -tags=e2e ./test/e2e/...With Prism you can run E2E tests earlier — even before the backend implementation is finished — because the OpenAPI contract is enough to validate the shape of requests and responses.
16.09 E2E Test: Register and Login Flow
The most valuable E2E tests exercise one complete user journey in a single function. The test below chains register → login → place order → cancel over real HTTP.
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}This single test simultaneously validates the JWT middleware, the auth flow, stock reservation, and the cancel rule — exactly what a real user experiences, in the correct order.
16.10 Coverage Target per Layer
Coverage is not a single number — each layer has a different target based on its risk. The target table below serves as both a guide and a CI gate.
1TARGET COVERAGE:
2
3Domain entities:
4 target: 90%+
5 rationale: business rules must be fully tested, no dependencies
6
7UseCase layer:
8 target: 85%+
9 rationale: every AC from the spec must have a test
10
11Repository layer:
12 target: 70%+ (integration tests)
13 rationale: SQL queries need a real DB for a 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/...The higher targets for domain and usecase reflect the principle: the closer code sits to business rules, the tighter the test coverage we demand.
16.11 Test Tags Strategy
So that test layers can run separately, we use Go build tags. The summary below maps each tag to its dependency needs and the command to run it.
1// Build tags for isolating test layers:
2
3// Unit tests: no tag needed (default)
4// go test ./...
5
6// Integration tests: need a test DB
7//go:build integration
8// go test -tags=integration ./...
9
10// E2E tests: need a running server
11//go:build e2e
12// go test -tags=e2e ./test/e2e/...
13
14// Benchmarks: for 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 e2eWith this tag split, developers can run unit tests lightning-fast on a laptop, while integration and E2E only fire when dependencies are available (locally or in CI).
16.12 Makefile Test Commands
Long test commands are best wrapped in a Makefile so they stay consistent between local and CI. The targets below separate unit, integration, E2E, and 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-integrationBecause these targets are used identically in CI, “works on my machine” becomes far harder — a command that fails locally will also fail in the pipeline.
16.13 Spec AC Traceability Matrix
The core of SDD is that every AC can be traced to its test. The traceability matrix below maps each feature, AC, test function, and layer.
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 + integrationThis matrix is what specify audit later reads to compute the spec compliance score — an AC without a row here means a feature that has not been proven to work.
16.14 Table-Driven Tests for Error Scenarios
When many scenarios are similar and only differ by input, a table-driven test is far more concise than writing separate functions. The example below tests many password validation variations in a single table.
1// For many similar error scenarios — use 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}Each row has a name, so when one case fails, the test output points straight at the problematic scenario without any guessing.
16.15 Testing the Redis Rate Limiter
A Redis-based rate limiter needs a real Redis instance to be tested properly. The setup helper below prepares a test Redis client that is automatically flushed when done.
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}Notice the use of DB: 1 as a separate test database — this prevents the test’s FlushDB from wiping development data that usually lives in DB 0.
Once the setup is ready, the rate limiter test below verifies that the 6th call is rejected after the first 5 calls pass.
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}This test locks down the “rate limit → 429” AC at the infrastructure level, ensuring the window and counter truly work in Redis rather than merely being assumed in the usecase logic.
16.16 Handler Test with httptest
Handlers can be tested in isolation using httptest without running a full server. The example below verifies that the register handler returns 201 with a mocked usecase.
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 tests focus on request parsing, validation, and response formatting — while the business logic is already tested separately in usecase unit tests, so there’s no duplicate coverage.
16.17 CI Test Pipeline Configuration
Every test layer must run automatically in CI with the right dependencies. The GitHub Actions configuration below runs unit tests with a coverage gate, then integration tests with PostgreSQL and Redis.
1# .github/workflows/test.yml (testing section)
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 spins up fresh PostgreSQL and Redis containers for each run, so integration tests always run against clean state without contamination between builds.
16.18 Race Condition Detection
Concurrency bugs are the most dangerous class because they often slip past review. The -race flag and the concurrent scenarios below are how we catch them before they reach production.
1# Always run tests with the -race flag
2go test -race ./...
3
4# Common race conditions that must be tested:
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 with stock 5
12# // Launch: 10 goroutines placing an order of qty 1 simultaneously
13# // Expect: 5 success, 5 ErrInsufficientStock
14# // Verify: reserved_stock == 5 (no more)
15# // Implementation: integration test with real DB + goroutines
16# // go test -race -tags=integration -run TestPlaceOrder_Concurrent
17# }The overselling scenario is the real exam: 10 goroutines fighting over the last 5 units must produce exactly 5 successes and 5 failures — and -race ensures there is no unsynchronized memory access throughout.
16.19 Test Data Management
Repeated test data setup is best wrapped in a builder so tests stay concise. The fixtures package below provides reusable constructors for users, products, and orders.
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}A constructor like NewUser produces a unique email via UUID, so tests running in parallel never collide on duplicate data.
16.20 Summary: The Santekno Shop Testing Strategy
Testing in Santekno Shop follows one principle: every AC from the spec must have at least one test that covers it. Three layers work together to make that happen.
Unit tests (150+ test cases): fast, isolated, covering all usecases and domain entities. Mocks are generated from interfaces.
Integration tests (50+ test cases): real PostgreSQL + Redis, verifying atomic transactions, SQL queries, and race conditions.
E2E tests (20 test cases): happy paths via HTTP, full stack, with the option of the Prism mock server.
CI gates: unit coverage ≥ 80%, specify audit ≥ 80, clean lint, and no race conditions. The traceability matrix guarantees all 29 ACs from the spec are covered, while the naming convention makes every failure easy to trace back to its spec.