A TestXxx function is a Go test function named with the Test<FunctionName> pattern and declared with a *testing.T parameter. It calls a function, compares the result with an expected value, and reports failures through testing.T. section 2.1.4
Structure each test around four phases:
- Preparation: set up inputs, expected outputs, environment variables, connections, or other required state. section 2.1.4
- Execution: call the function being tested, usually in a single line. section 2.1.4
- Decision: compare the result or state with the desired value and mark mismatches as failures. section 2.1.4
- Teardown: restore or remove altered state, often with defer. section 2.1.4
Testing greet
func TestGreet(t *testing.T) { want := "Hello world" got := greet() if got != want { t.Errorf("expected: %q, got: %q", want, got) } } section 2.1.4
Listing 2.4 main_internal_test.go: Testing greet
package main
import "testing"
func TestGreet(t *testing.T) {
want := "Hello world"
got := greet()
if got != want {
// mark this test as failed
t.Errorf("expected: %q, got: %q", want, got)
}
}
Browse the complete TestGreet test, including its testing import, expected value, function call, comparison, and failure report. section 2.1.4
