HTTP Tests
HTTP tests verify request handling at the controller, route group, or generated server boundary.
Use the smallest boundary that proves the behavior.
Controller Tests
Test a handler directly with webtest.NewContext when route registration and middleware are outside the behavior you need to prove. Pass its route pattern and path parameters explicitly.
Register the controller's routes as the App does to exercise route grouping and the body-limit middleware together.
Route Tests
After adding the POST endpoint in Requests and Validation, put this test in internal/users/controller_test.go. It checks the existing GET route, JSON binding, field errors, normalization, and the registered 16 KB body limit without a listener:
package users
import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/goforj/web"
"github.com/goforj/web/adapter/echoweb"
)
// TestUserRoutes verifies the registered routes and their public response contracts.
func TestUserRoutes(t *testing.T) {
adapter := echoweb.New()
controller := NewController(NewService())
group := web.NewRouteGroup("/api/v1", controller.Routes())
if err := web.RegisterRoutes(adapter.Router(), []web.RouteGroup{group}); err != nil {
t.Fatal(err)
}
largeBody := `{"display_name":"` + strings.Repeat("x", 17*1024) + `"}`
tests := []struct {
name, method, path, body string
status int
want string
chunked bool
}{
{"find user", http.MethodGet, "/api/v1/users/42", "", http.StatusOK,
`{"id":"42","name":"Ada Lovelace","email":"[email protected]"}`, false},
{"malformed JSON", http.MethodPost, "/api/v1/users", `{"email":`, http.StatusBadRequest,
`{"error":"invalid_payload"}`, false},
{"invalid fields", http.MethodPost, "/api/v1/users",
`{"display_name":" ","email":"x","password":"short"}`, http.StatusUnprocessableEntity,
`{"error":"validation_failed","fields":{"display_name":"required","email":"invalid_format","password":"too_short"}}`, false},
{"create user", http.MethodPost, "/api/v1/users",
`{"display_name":" Ada Lovelace ","email":" [email protected] ","password":"correct horse battery staple"}`, http.StatusCreated,
`{"id":"user_123","name":"Ada Lovelace","email":"[email protected]"}`, false},
{"body too large", http.MethodPost, "/api/v1/users", largeBody,
http.StatusRequestEntityTooLarge, http.StatusText(http.StatusRequestEntityTooLarge), false},
{"chunked body too large", http.MethodPost, "/api/v1/users", largeBody,
http.StatusRequestEntityTooLarge, http.StatusText(http.StatusRequestEntityTooLarge), true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
req := httptest.NewRequest(test.method, test.path, strings.NewReader(test.body))
req.Header.Set("Content-Type", "application/json")
if test.chunked {
req.ContentLength = -1
req.TransferEncoding = []string{"chunked"}
}
rec := httptest.NewRecorder()
adapter.ServeHTTP(rec, req)
if rec.Code != test.status {
t.Fatalf("status = %d, want %d; body = %s", rec.Code, test.status, rec.Body.String())
}
if test.status == http.StatusRequestEntityTooLarge {
if strings.TrimSpace(rec.Body.String()) != test.want {
t.Fatalf("body = %q, want %q", rec.Body.String(), test.want)
}
return
}
var got, want any
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("decode response: %v", err)
}
if err := json.Unmarshal([]byte(test.want), &want); err != nil {
t.Fatalf("decode expectation: %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("response = %v, want %v", got, want)
}
})
}
}
// TestCreateUserInputPreservesPassword verifies normalization leaves credentials unchanged.
func TestCreateUserInputPreservesPassword(t *testing.T) {
password := " correct horse battery staple "
request := createUserRequest{DisplayName: "Ada Lovelace", Email: "[email protected]", Password: password}
input, fields := request.input()
if len(fields) != 0 {
t.Fatalf("unexpected field errors: %v", fields)
}
if input.Password != password {
t.Fatal("normalization changed the password")
}
}Run from the app root:
go test ./internal/users -run 'Test(UserRoutes|CreateUserInputPreservesPassword)$'Expected result: the package reports ok; all six route cases and password preservation pass. The size checks cover both a declared content length and an unknown-length chunked body.
Use broader route or server tests for framework routes, middleware ordering, readiness failures, metrics, and Inspect integration. To verify the app's generated wiring and listener, follow Verify the Route and Try the Route.
Generated Health Tests
GoForj Apps include generated HTTP tests for framework routes when HTTP is enabled.
Common routes:
GET /-/healthGET /-/readyGET /swaggerGET /swagger/doc.jsonGET /metricswhen metrics are enabled
Readiness
Test readiness failures deliberately. Public readiness should be safe. Authorized readiness can expose structured details when called with APP_DIAG_TOKEN.
Next Steps
- Requests and Validation owns the POST implementation and request rules.
- Controllers explains controller boundaries.
- Middleware explains route policy.
- Integration Tests covers full boundary tests.