This repository accompanies the article Integration Testing in Go with Testcontainers and demonstrates how to build a simple CRUD application in Golang with robust testing practices. The project covers unit testing and integration testing against real infrastructure using Docker and Testcontainers.
- Create, Read, Update, Delete (CRUD) operations for notes with an
id,titleanddescription. - Layered architecture:
- Database Access Layer (DBAL): Handles all database interactions using pgx.
- Service Layer: Contains business logic.
- HTTP Layer: Exposes REST API endpoints.
- Integration tests with real PostgreSQL using Testcontainers.
- Unit tests with mocked dependencies.
Go 1.20or higher.- Docker.
make(optional, for running migrations).- PostgreSQL (if running outside Docker).
- Clone the repository
git clone https://github.com/the-code-genin/golang_integration_testing.git
cd golang_integration_testing- Initialize Go modules
go mod download- Set up PostgreSQL
(Optional) Using Docker:
docker run -p 5432:5432 -e POSTGRES_PASSWORD=password -d postgres:16.11Running migrations:
make migrate-upThis ensure we have a database with all migrations applied.
- Running the Server
Start the application:
go run .The server should start on port 8080 (or the port specified via env variables):
# [GIN-debug] Listening and serving HTTP on :8080migrations/- SQL migration files.repository/- Database Access Layer (DBAL).service/- Business logic layer.http/- REST API layer.tests/- Test helpers.main.go- Application entry point.Makefile- Optional automation commands.
POST /notes- Create a note with title and description.GET /notes/:id- Fetch a single note by ID.GET /notes- Fetch all notes.PUT /notes/:id- Update a note by ID.DELETE /notes/:id- Delete a note by ID.