> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reliantlabs.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Test a Go API against a real Postgres database

> Write table-driven Go tests that call your Connect handlers against a real Postgres with no Docker, and unit-test business logic with Forge's generated mocks.

By the end of this guide you have two kinds of test in a Forge Go API: table-driven tests that call your RPC handlers against a real Postgres, and a unit test of business logic that runs on a generated mock. Both run in the fast tier, with nothing to install and no Docker.

Forge projects its database code from your migrations, so the honest test runs those migrations on Postgres. The test harness boots one embedded Postgres per machine and gives each test its own database ([how Forge tests work](https://docs.reliantlabs.io/deep-dives/how-forge-tests-work.md)).

## Before you begin

* A Forge Go API with at least one entity, such as the `shop` project from [Add a database table with a CRUD API and pages](https://docs.reliantlabs.io/guides/forge/add-table-crud-api-pages.md). This guide uses its `catalog` service, with `products` and `reviews` tables.
* Go and `task` on your `PATH`. Docker is not needed.
* The project pinned to forge v1.6 or later (`reliant forge --version` inside the project).

**1. Run the tests Forge already wrote**

```bash terminal theme={null}
task test:short -- ./internal/...
```

```text terminal theme={null}
task: [test:short] go test -short -timeout 60s ./internal/...
?   	example.com/shop/internal/db	[no test files]
ok  	example.com/shop/internal/handlers/catalog	0.388s
```

That already ran `TestCRUD_Product_Lifecycle` from `handlers_crud_test.go` against a real Postgres, downloaded and started on first use. The lifecycle test covers the service's first entity only, and it replays every migration into a fresh database per test. The tests you write next use the faster path.

**2. Write a table test for your handlers**

`NewMigratedTestDB` gives a test a copy of a template database that has your migrations applied once. `NewProduct` inserts a valid row derived from the schema. `tdd.TableRPC` runs one subtest per case against the handler.

```go internal/handlers/catalog/catalog_table_test.go theme={null}
package catalog_test

import (
	"testing"

	"connectrpc.com/connect"
	"github.com/reliant-labs/forge/pkg/tdd"

	pb "example.com/shop/gen/services/catalog/v1"
	"example.com/shop/internal/db"
	catalog "example.com/shop/internal/handlers/catalog"
)

func TestGetProduct(t *testing.T) {
	database := catalog.NewMigratedTestDB(t) // a copy of the migrated template
	svc := catalog.NewTestCatalog(t, catalog.WithDB(database))
	ctx := catalog.AuthedContext(t)

	widget := catalog.NewProduct(t, database, func(p *db.Product) {
		p.Name = "Widget"
		p.PriceCents = 1999
	})

	tdd.TableRPC(t, []tdd.Case[pb.GetProductRequest, pb.GetProductResponse]{
		{
			Name: "returns the stored product",
			Ctx:  ctx,
			Req:  connect.NewRequest(&pb.GetProductRequest{Id: widget.ID}),
			Check: func(t *testing.T, resp *connect.Response[pb.GetProductResponse]) {
				p := resp.Msg.GetProduct()
				if p.GetName() != "Widget" || p.GetPriceCents() != 1999 {
					t.Errorf("got %q at %d cents, want Widget at 1999", p.GetName(), p.GetPriceCents())
				}
			},
		},
		{
			Name:    "unknown id is NotFound",
			Ctx:     ctx,
			Req:     connect.NewRequest(&pb.GetProductRequest{Id: "no-such-product"}),
			WantErr: connect.CodeNotFound,
		},
	}, svc.GetProduct)
}

func TestCreateReview(t *testing.T) {
	database := catalog.NewMigratedTestDB(t)
	svc := catalog.NewTestCatalog(t, catalog.WithDB(database))
	ctx := catalog.AuthedContext(t)
	widget := catalog.NewProduct(t, database)

	tdd.TableRPC(t, []tdd.Case[pb.CreateReviewRequest, pb.CreateReviewResponse]{
		{
			Name: "reviews a stored product",
			Ctx:  ctx,
			Req:  connect.NewRequest(&pb.CreateReviewRequest{ProductId: widget.ID, Rating: 5}),
		},
		{
			// Only a real database enforces reviews_product_id_fkey.
			Name:    "a missing product is a failed precondition",
			Ctx:     ctx,
			Req:     connect.NewRequest(&pb.CreateReviewRequest{ProductId: "no-such-product", Rating: 5}),
			WantErr: connect.CodeFailedPrecondition,
		},
	}, svc.CreateReview)
}
```

The last case is the reason to test on Postgres. A mocked store would accept the review; Postgres rejects it with the foreign key, and the handler returns `failed_precondition: create review: a referenced record is missing or still in use (constraint reviews_product_id_fkey)`. `AuthedContext` signs the call in as a test user, because the test calls the handler directly rather than through the auth middleware.

**3. Put business logic in a package with a contract**

Logic you want to test without a database goes in a package whose dependencies are interfaces:

```bash terminal theme={null}
reliant forge scaffold package pricing
```

Declare the method and the dependency in `contract.go`, and add the dependency to `Deps` in `service.go`:

```go internal/pricing/contract.go theme={null}
type Service interface {
	// WithTax returns cents plus the tax for region, rounded to the nearest cent.
	WithTax(ctx context.Context, cents int64, region string) (int64, error)
}

// TaxRates looks up a region's sales tax in basis points (725 = 7.25%).
type TaxRates interface {
	RateBasisPoints(ctx context.Context, region string) (int64, error)
}
```

```go internal/pricing/service.go theme={null}
type Deps struct {
	Logger *slog.Logger
	Config *config.Config
	Rates  TaxRates
}

// ErrNegativePrice is returned for a price below zero.
var ErrNegativePrice = errors.New("pricing: negative price")

func (s *service) WithTax(ctx context.Context, cents int64, region string) (int64, error) {
	if cents < 0 {
		return 0, ErrNegativePrice
	}
	bps, err := s.deps.Rates.RateBasisPoints(ctx, region)
	if err != nil {
		return 0, fmt.Errorf("tax rate for %s: %w", region, err)
	}
	return cents + (cents*bps+5000)/10000, nil
}
```

Then run `reliant forge generate`. It rewrites `mock_gen.go` with a mock for every interface in `contract.go`, here `MockService` and `MockTaxRates`.

> [!NOTE]
>
> `reliant forge lint` reports `forge-graph-unreachable` for `internal/pricing` until a service takes `pricing.Service` in its `Deps` and something provides `TaxRates`. That is wiring, not testing: the tests below run either way.

**4. Test it with the generated mock**

Program the mock by setting its `RateBasisPointsFunc`. `tdd.TableContract` runs each case and compares `Want` or matches `WantErr` with `errors.Is`. The mock records every call, so the last case also checks that a bad price never reached the rate lookup.

```go internal/pricing/contract_test.go theme={null}
package pricing_test

import (
	"context"
	"errors"
	"testing"

	"github.com/reliant-labs/forge/pkg/tdd"

	"example.com/shop/internal/pricing"
)

func TestContract(t *testing.T) {
	t.Parallel()

	errUnknownRegion := errors.New("unknown region")
	rates := &pricing.MockTaxRates{
		RateBasisPointsFunc: func(_ context.Context, region string) (int64, error) {
			if region == "CA" {
				return 725, nil // 7.25%
			}
			return 0, errUnknownRegion
		},
	}
	svc, err := pricing.New(pricing.Deps{Rates: rates})
	if err != nil {
		t.Fatalf("pricing.New: %v", err)
	}
	ctx := context.Background()

	tdd.TableContract(t, svc, []tdd.ContractCase{
		{
			Name: "adds the region's tax, rounded to the cent",
			Call: func() (any, error) { return svc.WithTax(ctx, 1999, "CA") },
			Want: int64(2144), // 1999 + 144.93
		},
		{
			Name:    "passes a rate lookup failure through",
			Call:    func() (any, error) { return svc.WithTax(ctx, 1999, "ZZ") },
			WantErr: errUnknownRegion,
		},
		{
			Name: "rejects a negative price before looking up a rate",
			Call: func() (any, error) {
				before := rates.CallCount("RateBasisPoints")
				_, err := svc.WithTax(ctx, -1, "CA")
				if after := rates.CallCount("RateBasisPoints"); after != before {
					t.Errorf("RateBasisPoints called %d time(s), want 0", after-before)
				}
				return nil, err
			},
			WantErr: pricing.ErrNegativePrice,
		},
	})
}
```

This replaces the scaffolded `contract_test.go`, which skips until it has cases.

**5. Run them and check they ran**

```bash terminal theme={null}
task test:short -- -v -run 'TestGetProduct|TestCreateReview|TestContract' ./internal/handlers/catalog/ ./internal/pricing/
```

```text terminal theme={null}
--- PASS: TestGetProduct (0.11s)
    --- PASS: TestGetProduct/returns_the_stored_product (0.00s)
    --- PASS: TestGetProduct/unknown_id_is_NotFound (0.00s)
--- PASS: TestCreateReview (0.09s)
    --- PASS: TestCreateReview/reviews_a_stored_product (0.00s)
    --- PASS: TestCreateReview/a_missing_product_is_a_failed_precondition (0.00s)
ok  	example.com/shop/internal/handlers/catalog	0.213s
--- PASS: TestContract (0.00s)
    --- PASS: TestContract/adds_the_region's_tax,_rounded_to_the_cent (0.00s)
    --- PASS: TestContract/passes_a_rate_lookup_failure_through (0.00s)
    --- PASS: TestContract/rejects_a_negative_price_before_looking_up_a_rate (0.00s)
ok  	example.com/shop/internal/pricing	0.013s
```

Every case is listed as its own subtest. Run the fast tier again without changes and the unchanged packages print `(cached)`. Before you finish, run the full tier on the packages you touched, with the race detector and no cache:

```bash terminal theme={null}
task test -- ./internal/handlers/catalog/... ./internal/pricing/...
```

```text terminal theme={null}
task: [test]  go test -race -count=1 -timeout 120s ./internal/handlers/catalog/... ./internal/pricing/...
ok  	example.com/shop/internal/handlers/catalog	1.529s
ok  	example.com/shop/internal/pricing	1.042s
```

## What this does not do

* **It doesn't test through the network.** These tests call handler methods directly, so the auth middleware and interceptors do not run. `NewTestCatalogServer` in the generated `helpers_gen_test.go` serves the service over HTTP with a typed client when you need that.
* **It doesn't write a lifecycle test for later entities.** Only a service's first entity gets one. Use the factories (`NewReview`, `NewCreateReviewRequest`) in tests like the ones above.
* **It doesn't mark slow tests for you.** A test that runs a subprocess or takes more than about two seconds calls `testkit.Slow(t, "<why>")` first, so it skips under `-short` ([how Forge tests work](https://docs.reliantlabs.io/deep-dives/how-forge-tests-work.md#two-tiers-and-where-each-test-runs)).

## Troubleshooting

> [accordion] tax rate for CA: MockTaxRates.RateBasisPointsFunc not set
>
> A generated mock returns this error from any method you did not program, instead of a zero value. Set `RateBasisPointsFunc` (or the `…Func` field the message names) on the mock before the call.

> [accordion] internal: get product failed
>
> Every call fails with `internal` when the service runs on the default database, which is empty: `NewTestCatalog(t)` with no `WithDB` creates no tables. The handler hides the database error from the caller. Pass `catalog.WithDB(catalog.NewMigratedTestDB(t))`.

## Next steps

> [card] [How Forge tests work](https://docs.reliantlabs.io/deep-dives/how-forge-tests-work.md)
>
> The shared Postgres, template copies, the two tiers and why a skipped test never counts as a pass.

> [card] [Add a database table with a CRUD API and pages](https://docs.reliantlabs.io/guides/forge/add-table-crud-api-pages.md)
>
> Add the entity whose handlers these tests call.

> [card] [Contracts and generated mocks](https://docs.reliantlabs.io/forge/concepts/contracts-and-injection.md#generated-mocks)
>
> `contract.go`, `Deps` and what `mock_gen.go` holds.

> [card] [Generated vs yours](https://docs.reliantlabs.io/forge/concepts/generated-vs-yours.md)
>
> Which test files Forge regenerates and which you own.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.