Go Testing Paketi: Unit Test Yazmanın Temel Adımları
Go'da test yazmak basit. Dil, testing için yerleşik bir paket sunuyor ve özel bir dosya adlandırma kuralı kullanıyor.
Test dosyaları `_test.go` ile bitmeli. Örneğin ana dosyan `math.go` ise test dosyası `math_test.go` olacak. Go, bu kuralı görünce test dosyasını otomatik olarak tanır.
Test fonksiyonları `Test` ile başlamalı ve `*testing.T` parametresi almalı:
1func TestAdd(t *testing.T) {2result:= Add(2, 3)3if result!= 5 {4t.Errorf("Add(2, 3) = %d; istenen 5", result)5}6}Test etmek için bir fonksiyon gerekli. `math.go` dosyasında:
1package main23func Add(a, b int) int {4return a + b5}`math_test.go` dosyasında:
1package main23import "testing"45func TestAdd(t *testing.T) {6tests:= []struct {7name string8a, b int9expected int10}{11{"pozitif sayılar", 2, 3, 5},12{"negatif sayılar", -1, -2, -3},13{"sıfır ile", 0, 5, 5},14}1516for _, tt:= range tests {17t.Run(tt.name, func(t *testing.T) {18result:= Add(tt.a, tt.b)19if result!= tt.expected {20t.Errorf("Add(%d, %d) = %d; istenen %d", tt.a, tt.b, result, tt.expected)21}22})23}24}Terminalde:
1go testBeklenen çıktı:
1ok _/home/user/project 0.001sTest başarısız olursa:
1go test -vBu, her test için ayrıntılı bilgi gösterir.
Bazı fonksiyonlar hata döndürür. Bunu da test edebilirsin:
1func Divide(a, b int) (int, error) {2if b == 0 {3return 0, errors.New("sıfıra bölme")4}5return a / b, nil6}78func TestDivide(t *testing.T) {9_, err:= Divide(5, 0)10if err == nil {11t.Error("Divide(5, 0) hatası beklendi")12}13}Go'da test yazmak üç adımda özetlenebilir: dosyayı `_test.go` ile adlandır, `Test` ile başlayan fonksiyon yaz, `t.Error` veya `t.Errorf` ile hataları kontrol et. `go test` komutu tüm testleri çalıştırır. Birden fazla test senaryosu için tablo tabanlı yaklaşım (struct slice) kullan; bu sayede kodun temiz ve bakımlanabilir kalır.
0 yorum