The Go testing package supplies standard-library support for writing and running tests, examples, and benchmarks. It avoids the need to build custom testing tools or adopt independent libraries. section 2.1.4 section 2.6
A conventional test function has the signature Test<FunctionName>(t *testing.T). Its usual workflow is preparation, execution, decision, and teardown: set inputs and expectations, call the function, compare the result, and restore resources. section 2.1.4
Practical testing patterns include:
- Use t.Errorf to report a mismatch between an expected value and the value returned by the function under test. section 2.1.4
- Split distinct scenarios into names such as TestGreet_English and TestGreet_French; include unknown or unsupported inputs to check safety nets. section 2.2.2
- Use table-driven tests to iterate through structured cases containing multiple inputs and expected outputs. section 2.6
- Run tests with go test, following Go’s naming conventions for test files and functions. section 2.6
Testing greet
package main import "testing" func TestGreet(t *testing.T) { want := "Hello world" got := greet() if got != want { t.Errorf("expected: %q, got: %q", want, got) } }
Listing 2.8 main_internal_test.go: Split test cases
package main
import "testing"
func ExampleMain() {
...
}
func TestGreet_English(t *testing.T) {
lang := language("en") #1
want := "Hello world"
got := greet(lang) #2
if got != want { #3
// mark this test as failed
t.Errorf("expected: %q, got: %q", want, got)
}
}
func TestGreet_French(t *testing.T) {
lang := language("fr") #1
want := "Bonjour le monde"
got := greet(lang) #2
if got != want { #3
// mark this test as failed
t.Errorf("expected: %q, got: %q", want, got)
}
}
func TestGreet_Akkadian(t *testing.T) {
// Akkadian is not implemented yet!
lang := language("akk") #1
want := ""
got := greet(lang) #2
if got != want { #3
// mark this test as failed
t.Errorf("expected: %q, got: %q", want, got)
}
}
Compare separate scenario tests for English, French, and an unimplemented language. section 2.2.2

