How to set up a Go project with modules and tests
Set up a Go project with modules: initialize go.mod, structure a package, manage dependencies with go mod tidy, and write table-driven tests with the standard testing package.
What Go modules give you
Go modules are Go's built-in dependency and versioning system. A module is a collection of packages defined by a go.mod file at its root. Modules make builds reproducible and remove the old reliance on a single workspace path. Go also ships a testing framework in the standard library, so you need no extra tools to test.
Prerequisites
- Go 1.21 or later installed
- A terminal
Steps
1. Initialize a module
Create a directory and initialize the module with a path, usually your repository URL.
mkdir greeter && cd greeter
go mod init example.com/greeter
This writes go.mod.
2. Create a package
Add a file with a function to test.
package greeter
func Greet(name string) string {
if name == "" {
name = "world"
}
return "hello, " + name
}
3. Add a dependency
Adding an import and running go mod tidy records dependencies and downloads them.
go mod tidy
4. Write a table-driven test
Go's idiomatic style runs many cases from a slice of structs.
package greeter
import "testing"
func TestGreet(t *testing.T) {
cases := []struct{ in, want string }{
{"Ada", "hello, Ada"},
{"", "hello, world"},
}
for _, c := range cases {
if got := Greet(c.in); got != c.want {
t.Errorf("Greet(%q) = %q, want %q", c.in, got, c.want)
}
}
}
5. Run tests and coverage
go test ./...
go test -cover ./...
6. Build the binary
For an executable, create package main with a main function, then build.
go build ./...
Verification
Run go test ./... and confirm all tests pass. Break a case deliberately and confirm the test fails with a clear message, then fix it. Run go vet ./... to catch common mistakes.
Next Steps
Add benchmarks with testing.B, use t.Run subtests for clearer output, set up golangci-lint, and wire go test ./... into continuous integration.
Prerequisites
- Go 1.21+ installed
- Basic command line familiarity
Steps
- 1Initialize a module
- 2Create a package
- 3Add a dependency
- 4Write a table-driven test
- 5Run tests and coverage
- 6Build the binary