How to Test Database Code in Go (Integration Testing)

Run Go database integration tests using the testing package with in-memory databases and cleanup functions to verify real SQL interactions.

Use the testing package with t.Run subtests to isolate database operations and t.Cleanup to reset state between tests.

func TestUserRepo(t *testing.T) {
    db, cleanup := setupTestDB(t)
    defer cleanup()

    t.Run("Insert", func(t *testing.T) {
        err := db.InsertUser("alice")
        if err != nil { t.Fatal(err) }
    })

    t.Run("Select", func(t *testing.T) {
        user, err := db.GetUser("alice")
        if err != nil { t.Fatal(err) }
        if user.Name != "alice" { t.Fatal("wrong name") }
    })
}

func setupTestDB(t *testing.T) (*DB, func()) {
    db, err := NewDB("sqlite3", ":memory:")
    if err != nil { t.Fatal(err) }
    return db, func() { db.Close() }
}

Run the tests with go test -v ./....