Best Practices

Testing

To run all tests in a Go project:


$ go test ./...

To list all Go packages in project:


$ go list ./...

Mocking

Go has a easy to use tool for mocking interfaces in Go. Install https://github.com/uber-go/mock You can mock a file with an interface.

Usage:

This will give you the mocked file outputted to stdout.

$ mockgen -source interface.go
$ mockgen -source interface.go -package mocks -destination ./mocks/interface_mock.go

You can then write tests which use interface_mock.go

Go Leak

A tool https://github.com/uber-go/goleak that helps with detecting go routine leaks during testing.

To verify that there are no unexpected goroutines running at the end of a test:

func TestA(t *testing.T) {
	defer goleak.VerifyNone(t)
	// test logic here.
}

Instead of checking for leaks at the end of every test, goleak can also be run at the end of every test package by creating a TestMain function for your package:

func TestMain(m *testing.M) {
	goleak.VerifyTestMain(m)
}