package module
Version: v0.0.0-...-a835544 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2021 License: MIT Imports: 7 Imported by: 17


Dockertest Build Status

dockertest allows you to quickly and easily test database interactions by creating and destroying databases within your tests using docker.

It works by controlling the docker daemon running locally with exec.Command. The flow is as follows ->

  1. find a free port on the local machine
  2. launch docker container and bind that port
  3. wait until the container needs to be shutdown

dockertest is inspired by and - however, it does not add 300k loc of dependencies (guesstimated) to your project. See for more info on this.


go get -u

currently the tests depend on

How good is it?

Currently the manipulation of the docker daemon is somewhat fragile, as it depends on exec.Command and a well placed time.Sleep for shutdown. In an ideal world, this would use the docker api via the docker socket directly, but it currently works well enough for now. Contributions welcome


Postgres example copied from

func TestDBBits(t *testing.T) {
	container, err := dockertest.RunContainer("postgres:alpine", "5432", func(addr string) error {
		db, err := sql.Open("postgres", "postgres://postgres:postgres@"+addr+"?sslmode=disable")
		if err != nil {
			return err

		return db.Ping()
	defer container.Shutdown()
	if err != nil {
		t.Fatalf("could not start postgres, %s", err)

	db, err := sql.Open("postgres", "postgres://postgres:postgres@" + container.Addr + "?sslmode=disable")
	if err != nil {

	// run tests on the db, etc

It should be trivial to adapt the above bits to work just as well from a TestMain function, if you want to avoid running a new container for each individual test function - subtests also help here.

Docker-machine host

Note that dockertest will give priority to the DOCKER_MACHINE_NAME when looking for your container address and will fallback to localhost if it fails to find it.






This section is empty.


This section is empty.


This section is empty.


type Container

type Container struct {
	Name string
	Args []string
	Addr string
	// contains filtered or unexported fields

A Container is a container inside docker

func RunContainer

func RunContainer(container string, port string, waitFunc func(addr string) error, args ...string) (*Container, error)

RunContainer runs a given docker container and returns a port on which the container can be reached

func (*Container) Shutdown

func (c *Container) Shutdown()

Shutdown ends the container

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL