A test function is a Go function that the go test tool recognizes by convention: it belongs in a *_test.go file, begins with Test, accepts a *testing.T parameter, and returns no value. The file is excluded from normal builds but compiled for testing. section 8.1 section 8.3
Use the test function to:
- Arrange test data and expected results, act by calling the code under test, and assert the outcome. section 8.3
- Report failures through the testing.T parameter, using messages that explain both the expectation and the actual result. section 8.3
- Run automatically with go test; a test passes unless it times out, panics, or explicitly fails. section 8.2
Minimal executable test
In example_test.go, define: func TestPass(t *testing.T) { t.Log("This test will pass.") }. Running go test discovers the function and reports the package result; go test -v also displays its log and run status. section 8.2
Listing 8.4 An example test
func TestMyFeature(t *testing.T) {
// 1. Define some test data.
arg := "my data"
// 2. Define an expected result.
want := "expected value"
// 3. Interact with your code and get some data.
got := FunctionToTest(arg)
// 4. Inspect the results.
if got != want {
// 5. Mark the test as failed, and log the reason why.
t.Errorf("bad result - want: %v, got %v", want, got)
}
}
Shows a complete test with input data, an expected value, a function call, comparison, and t.Errorf failure reporting. section 8.3
