Test HTTP and database boundaries
Test HTTP and database boundaries
A boundary test checks the contract where your component meets another system. Start with an HTTP handler and a recorder to assert status, headers and body. Then test the repository against database/sql. A test double can model missing rows and driver errors, but only a real engine can establish SQL syntax, constraints, isolation and migration behavior.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "io" "net/http" "net/http/httptest" "testing")
func TestLesson(t *testing.T) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(http.StatusCreated) io.WriteString(w, "created") }) rec := httptest.NewRecorder() handler.ServeHTTP(rec, httptest.NewRequest("POST", "/books", nil)) res := rec.Result() defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil || res.StatusCode != 201 || res.Header.Get("Content-Type") != "text/plain" || string(body) != "created" { t.Fatal(res.StatusCode, string(body), err) }}Recorder.Result exposes a response snapshot. The handler test is deterministic and does not open a socket. For client transport, TLS and redirect behavior use httptest.NewServer or NewTLSServer and close them with Cleanup. Do not equate an in-process handler test with network coverage.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonCheck missing rows at the database/sql boundary
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "context" "database/sql" "errors" "testing")
func TestLesson(t *testing.T) { db := openFixture("ok") t.Cleanup(func() { if err := db.Close(); err != nil { t.Error(err) } }) var name string if err := db.QueryRowContext(context.Background(), "SELECT name FROM books WHERE id = ?", 7).Scan(&name); err != nil || name != "Go" { t.Fatal(name, err) } if err := db.QueryRowContext(context.Background(), "SELECT name FROM books WHERE id = ?", 99).Scan(&name); !errors.Is(err, sql.ErrNoRows) { t.Fatal(err) }}
--- fixture.go ---package lesson
import ( "context" "database/sql" "database/sql/driver" "errors" "io")
// fixtureDriver is a teaching double, not a SQL engine.type fixtureDriver struct{}type fixtureConn struct{ mode string }type fixtureTx struct{}type fixtureRows struct { values [][]driver.Value fail bool index int}
func (fixtureDriver) Open(name string) (driver.Conn, error) { if name == "offline" { return nil, errors.New("fixture offline") } return &fixtureConn{mode: name}, nil}func (c *fixtureConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not implemented in fixture")}func (c *fixtureConn) Close() error { return nil }func (c *fixtureConn) Begin() (driver.Tx, error) { return &fixtureTx{}, nil }func (c *fixtureConn) Ping(ctx context.Context) error { return ctx.Err() }func (t *fixtureTx) Commit() error { return nil }func (t *fixtureTx) Rollback() error { return nil }func (c *fixtureConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { if err := ctx.Err(); err != nil { return nil, err } switch q { case "SELECT name FROM books WHERE id = ?": if len(args) != 1 { return nil, errors.New("one argument required") } if args[0].Value == int64(7) { return &fixtureRows{values: [][]driver.Value{{"Go"}}}, nil } return &fixtureRows{}, nil case "SELECT name FROM books": return &fixtureRows{values: [][]driver.Value{{"Go"}, {nil}}, fail: c.mode == "broken"}, nil default: return nil, errors.New("unsupported fixture query") }}func (c *fixtureConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) { if err := ctx.Err(); err != nil { return nil, err } if q != "UPDATE books SET name = ? WHERE id = ?" || len(args) != 2 { return nil, errors.New("unsupported fixture update") } if args[1].Value == int64(7) { return driver.RowsAffected(1), nil } return driver.RowsAffected(0), nil}func (r *fixtureRows) Columns() []string { return []string{"name"} }func (r *fixtureRows) Close() error { return nil }func (r *fixtureRows) Next(dest []driver.Value) error { if r.index == len(r.values) { if r.fail { return errors.New("fixture stream interrupted") } return io.EOF } copy(dest, r.values[r.index]) r.index++ return nil}func must(err error) { if err != nil { panic(err) }}func openFixture(mode string) *sql.DB { db, err := sql.Open("bytemind-fixture", mode) must(err) return db}func init() { sql.Register("bytemind-fixture", fixtureDriver{}) }The included driver is the V101 teaching fixture. It accepts a small fixed query set and returns synthetic rows; it does not parse SQL or enforce constraints. Scan returns sql.ErrNoRows when the query has no rows. In a separate integration suite use the actual driver, a disposable database with production-compatible version and migrations, known fixtures, unique schemas or isolated databases, and cleanup. Assert actual constraints and rollback, not only mocked return values. Never run destructive tests against production.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Use a local httptest server returning 404 and assert that the client gets a response (not a transport error). Close the response and server. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced testing 02: Test HTTP and database boundaries
Check the lesson objective before moving on.
What does a fake SQL driver not establish?
What does an HTTP 404 normally mean for Client.Get?