Go has two features to make testing a core component:
- the testing command
go test ...
- the testing package
testing
By convention, tests live in the same folder as the package files and have the filename X_test.go for every X.go. If you'd like to test unexported names, the package name of the test must match the package it's testing. Otherwise, you can name the package X_test to test only exported names.
To run tests, you can navigate to the directory that contains tests and run go test
or go test X_test.go
.
If you'd like to run all tests for a project, navigate to the root of the project and run go test ./...
Let's look at an example test file:
package main // or main_test
func TestSomething(t *testing.T) {
// Include logic here
t.Error("Failed because of ...")
}
Functions must be named TestX if they are to be run with go test
.
Go does not include assertions and instead guides users to use if statements to trigger t.Error
s. However, there are 3rd party testing frameworks if assertions are what you need.
Implement tests for the square root function in 4.2
- Table Driven Tests are a great way to organize many test cases.
- Look at the tests in each test/ directory in this repo.
- Explore the math/rand stdlib tests by inspecting
GOOROOT/src/math/rand
.