HTTP Integration Tests
HTTP integratsion testlari
Bitta handler'ni emas, butun router (ServeMux)ni — turli yo'llar to'g'ri handler'larga yo'naltirilishini — birgalikda sinash "integratsion test" deyiladi. Jadval asosidagi test bilan bir nechta yo'lni bitta testda tekshirish mumkin.
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func setupMux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /status", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ishlayapti"))
})
mux.HandleFunc("GET /missing", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
})
return mux
}
func TestRoutes(t *testing.T) {
mux := setupMux()
tests := []struct {
name string
path string
want int
}{
{"mavjud yo'l", "/status", http.StatusOK},
{"mavjud bo'lmagan yo'l", "/missing", http.StatusNotFound},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest("GET", tc.path, nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != tc.want {
t.Errorf("status = %d, kutilgan %d", rec.Code, tc.want)
}
})
}
}setupMux() — router'ni bir joyda quradi, uni ham asosiy dasturda, ham testda ishlatish mumkin. mux.ServeHTTP(rec, req) esa haqiqiy so'rovni router orqali o'tkazadi — xuddi haqiqiy server ichida bo'lgandek, faqat tarmoqsiz. Bu naqsh butun API'ning "yo'llar to'g'ri ulanganmi" degan savoliga javob beradi.
>_ Exercise
Ikkita yo'lli router'ni integratsion test bilan tekshiring.
- •"/ok" 200, "/forbidden" 403 qaytaradigan router yozing
- •jadval asosida ikkalasini ham t.Run bilan tekshiring
Stuck? Reveal a hint to help you.
Key Takeaway
Key Takeaway:
Integratsion testlar butun router'ning (ko'plab yo'llarning birgalikda) to'g'ri ishlashini tekshiradi — alohida handler testlaridan bir qadam kattaroq ishonch beradi.
NEXT UP
Mocking Dependencies
$ go run main.go
Kodingizni ishga tushiring