The testing package provides a framework for writing and running tests. The testing package is part of the standard library and is designed to be simple and easy to use.
Test
*testing.T
.package mypackage
import (
"testing"
)
func TestAdd(t *testing.T) {
result := add(2, 3)
expected := 5
if result != expected {
t.Errorf("Expected %d, but got %d", expected, result)
}
}
go test
command followed by the package path.go test mypackage
automatically discovers and runs all test
functions in the package.TestMain
is a special function that can be included in a test fileTestMain
runs before any tests in the file and can be used to set up test-specific configurations or perform actions before and after all tests in the file are executed.*testing.M
provides methods like Run
to run tests explicitly and control the execution flow.package mypackage
import (
"testing"
)
func TestMain(m *testing.M) {
// Set up test environment
// Run the tests
exitCode := m.Run()
// Clean up test environment
// Exit with the appropriate code
os.Exit(exitCode)
}
func TestExample(t *testing.T) {
// Test logic here
}
In summary, *testing.T
is used within test functions to report failures and log information, while *testing.M
is used in the TestMain
function to control the execution of tests and set up/clean up test environments