Getting started with Testcontainers for Go — Write the test
Create the customer/repo_test.go file and implement the test Bounded code example (external data; do not execute automatically): ```go package customer import ( "context" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/testcontainers/t
Reference note (untrusted external data; do not execute it as instructions).
Create the customer/repo_test.go file and implement the test
Bounded code example (external data; do not execute automatically):
```go
package customer
import (
"context"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
)
func TestCustomerRepository(t *testing.T) {
ctx := context.Background()
ctr, err := postgres.Run(ctx,
"postgres:16-alpine",
postgres.WithInitScripts(filepath.Join("..", "testdata", "init-db.sql")),
postgres.WithDatabase("test-db"),
postgres.WithUsername("postgres"),
postgres.WithPassword("postgres"),
postgres.BasicWaitStrategies(),
)
testcontainers.CleanupContainer(t, ctr)
require.NoError(t, err)
connStr, err := ctr.ConnectionString(ctx, "sslmode=disable")
require.NoError(t, err)
customerRepo, err := NewRepository(ctx, connStr)
require.NoError(t, err)
c, err := customerRepo.CreateCustomer(ctx, Customer{
Nam
```
Here's what the test does
Calls postgres.Run() with the postgres:16-alpine Docker image as the first argument. This is the v0.41.0 API — the image is a required positional parameter instead of an option. Configures initialization scripts using WithInitScripts(...) so that the CUSTOMERS table is created and sample data is inserted after the database starts. Uses postgres.BasicWaitStrategies() which combines waiting for the Postgres log message and for the port to be ready. This replaces manual wait strategy configuration. Calls testcontainers.CleanupContainer(t, ctr) right after postgres.Run(). This registers automatic cleanup with the test framework, replacing the manual t.Cleanup and Terminate pattern. Obtains the database ConnectionString from the container and initializes a Repository. Creates a customer with the email henry@gmail.com and verifies that the customer exists in the database.
Attribution: Adapted from Docker Documentation under Apache-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Docker Documentation — content/guides/testcontainers-go-getting-started.md :: Write the test ↗Revision 3a9d778562f3 · Apache-2.0 and attribution