Testing
Controller Tests
Test controller behavior through routes and focused constructors.
Prefer route-level controller tests
Most controller behavior is best tested through the application handler:
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/posts/missing", nil)
appinit.App().ServeHTTP(response, request)
if response.Code != http.StatusNotFound {
t.Fatalf("status = %d", response.Code)
}
This verifies routing, controller construction, action behavior, rendering, and error handling together.
Check rendered data
Assert the observable response:
body := response.Body.String()
if !strings.Contains(body, "Posts") {
t.Fatalf("body does not contain title: %s", body)
}
Avoid reaching into controller internals unless the behavior cannot be observed from the HTTP response.
Test constructors when wiring matters
Constructor tests are useful for dependency requirements:
_, err := posts.New(context.Background())
if err == nil {
t.Fatal("expected missing posts service error")
}
Keep those tests focused on dependency resolution. Use HTTP tests for request behavior.