Test-Driven-Development-in-Go
This repository contains the code examples corresponding to the book Test-Driven Development in Go, published by Packt.
Dependencies
You will need the following tools to run your the code in this repository:
This project depends on a variety of testing tools, which are used for instruction and demonstration purposes:
Run locally
From Chapter06
onwards, you will require a database to run the BookSwap
application:
- Install PostgresSQL according to the installation steps for your operating system.
- Export the following user variables:
$ export BOOKSWAP_DB_URL=XXX
$ export BOOKSWAP_PORT=XXX
$ export BOOKSWAP_BASE_URL=XXX
- Run the
BookSwap
executable using the go run chapterXX/cmd/main.go
command. The application will then listen on the configured port.
Run in Docker
From chapter06
onwards, you can run the BookSwap
application with Docker:
- Install Docker according to the installation steps for your operating system. Separate Docker configuration files have been provided for each chapter. For example,
docker-compose.book-swap.chapter06.yml
runs the version of the application corresponding to the chapter06
directory.
- Create a
docker.env
file will all the variables required for running the application. Example values can be seen below:
POSTGRES_USER=root
POSTGRES_PASSWORD=root
POSTGRES_DB=books
BOOKSWAP_DB_URL=postgres://root:root@db:5432/books?sslmode=disable
BOOKSWAP_PORT=3000
- Run the application using
docker compose
:
$ docker compose -f docker-compose.book-swap.chapterXX.yml up --build
$ docker compose -f docker-compose.book-swap.chapterXX.yml down
- The application will then listen on the configured port.
curl --location --request GET 'http://localhost:3000/
Generate mocks
$ mockery --dir "chapterXX" --output "chapterXX/mocks" --all
Run unit tests
- Install all Dependencies and follow the Run locally steps.
- Run all tests:
$ go test ./... -v
Run all tests
WARNING: as tests often require a specific version of the test endpoint to be running, I do not recommend running all tests from the root directory.
Instead, I recommend running unit & integration tests per chapter:
- Run the Docker version of the
chapterXX
according to Run in Docker.
- In a separate window, change to the desired directory
cd chapterXX
.
- Run all tests in the
chapterXX
directory by setting to LONG
commandline argument:
$ LONG=true go test ./... -v
Postman collection
For your convenience, a Postman collection with requests for the BookSwap application has been provided. See BookSwap.postman_collection.json
. This file can then be used to import the collection into Postman.