Testing pertama yang akan kita buat adalah untuk routes.
Buat file baru cmd/web/routes_test.go, masukan kode testing dibawah:
package main
import (
"net/http"
"strings"
"testing"
"github.com/go-chi/chi/v5"
)
func Test_application_routes(t *testing.T) {
var registered = []struct {
route string
method string
}{
{"/", "GET"},
{"/static/*", "GET"},
}
var app application
mux := app.routes()
chiRoutes := mux.(chi.Routes)
for _, route := range registered {
//check if the route exists
if !routeExists(route.route, route.method, chiRoutes) {
t.Errorf("route %s is not registered", route.route)
}
}
}
func routeExists(testRoute, testMethod string, chiRoutes chi.Routes) bool {
found := false
_ = chi.Walk(chiRoutes, func(method string, route string, handler http.Handler, middleware ...func(http.Handler) http.Handler) error {
if strings.EqualFold(method, testMethod) && strings.EqualFold(route, testRoute) {
found = true
}
return nil
})
return found
}
Routes yang kita miliki sekarang adalah / dan /static.
Jalankan test dengan perintah berikut.
$ go test ./...
ok webapp/cmd/web 0.214s
Tips, perintah diatas akan menjalankan semua test dalam current directory dan sub directory.
Sesuai ekspektasi, test berhasil dijalankan.