การเขียนโปรแกรมที่ดี ไม่ได้จบแค่การให้ฟังก์ชันทำงานได้ แต่ต้องสามารถ “ทดสอบ” ได้ด้วย ซึ่งในภาษา Go นั้น มีความสามารถในการทดสอบที่เรียบง่ายแต่ทรงพลังมาก
ทำไมต้องเขียน Test?
- ป้องกัน regression
- ช่วยให้ refactor ได้อย่างมั่นใจ
- ทำงานร่วมกับทีมได้ราบรื่น
- ช่วยตรวจสอบ edge cases
รูปแบบการ Test ที่นิยมใน Go
- Unit Test: ทดสอบ function เดี่ยว ๆ
- Table Driven Test: ทดสอบหลายเคสด้วยตารางข้อมูล
- Mocking: ทดสอบแบบไม่ต้องพึ่ง dependency จริง
เริ่มต้นเขียน Unit Test
// math.go package mathlib func Add(a, b int) int { return a + b } // math_test.go package mathlib import "testing" func TestAdd(t *testing.T) { result := Add(2, 3) if result != 5 { t.Errorf("Expected 5 but got %d", result) } }
รันด้วยคำสั่ง:
go test
Table Driven Test
เหมาะกับฟังก์ชันที่ต้องรองรับหลาย input/output
func TestAddTable(t *testing.T) { tests := []struct { name string a, b int want int }{ {"add positives", 2, 3, 5}, {"add negatives", -1, -2, -3}, {"zero", 0, 0, 0}, } go คัดลอก แก้ไข for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := Add(tt.a, tt.b) if got != tt.want { t.Errorf("got %d, want %d", got, tt.want) } }) } }
Mocking ใน Go
Go ไม่มี mocking framework built-in แต่สามารถใช้ interface แทน dependency
ตัวอย่างระบบสั่งซื้อสินค้า
type PaymentGateway interface { Charge(amount float64) error } type OrderService struct { PG PaymentGateway } func (o *OrderService) Checkout(amount float64) error { return o.PG.Charge(amount) }
สร้าง mock ด้วย struct
type MockPayment struct { Called bool } func (m *MockPayment) Charge(amount float64) error { m.Called = true return nil } func TestCheckout(t *testing.T) { mock := &MockPayment{} service := OrderService{PG: mock} go คัดลอก แก้ไข err := service.Checkout(100) if err != nil || !mock.Called { t.Errorf("Payment not called") } }
คำสั่งเสริมในการ Test
go test -v
: แสดง loggo test -cover
: วัด coveragego test ./...
: test ทั้งโปรเจค
ภาพประกอบการทดสอบใน Go

สรุป
การเขียนเทสใน Go ไม่จำเป็นต้องใช้ framework ใหญ่ เพียงใช้ testing
package ก็สามารถเขียนเทสได้ทุกระดับ ทั้ง Unit Test, Table Driven Test และ Mocking ช่วยให้โปรเจคของคุณมั่นคง มีคุณภาพ และน่าเชื่อถือในระยะยาว
เผยแพร่โดย: poolsawat.com | เขียนโดย: King Pool