How to Write Tests in Go: Simple Guide with Examples
In Go, write tests by creating functions starting with
Test in a file ending with _test.go. Use the testing package and the *testing.T parameter to check conditions and report failures.Syntax
To write a test in Go, create a function with the name starting with Test followed by a descriptive name. The function must accept a single parameter of type *testing.T. Place this function in a file ending with _test.go. Use methods like t.Error or t.Fatal to report test failures.
go
func TestFunctionName(t *testing.T) {
// test code here
if got != want {
t.Errorf("got %v, want %v", got, want)
}
}Example
This example shows a simple function that adds two integers and a test function that checks if the addition works correctly.
go
package main import "testing" func Add(a, b int) int { return a + b } func TestAdd(t *testing.T) { got := Add(2, 3) want := 5 if got != want { t.Errorf("Add(2, 3) = %d; want %d", got, want) } }
Common Pitfalls
Common mistakes include naming test functions incorrectly (not starting with Test), forgetting the *testing.T parameter, or placing tests in files without the _test.go suffix. Also, not using the testing methods like t.Error or t.Fatal means failures won't be reported properly.
go
package main import "testing" // Wrong: missing *testing.T parameter func TestAdd() { // test code } // Correct: func TestAdd(t *testing.T) { // test code }
Quick Reference
| Concept | Description |
|---|---|
| Test function name | Must start with 'Test' and be exported (capitalized) |
| Test file name | Must end with '_test.go' |
| Test function parameter | Must accept '*testing.T' |
| Report failure | Use 't.Error', 't.Errorf', or 't.Fatal' |
| Run tests | Use 'go test' command in terminal |
Key Takeaways
Test functions must start with 'Test' and accept '*testing.T' as a parameter.
Place tests in files ending with '_test.go' to be recognized by Go tools.
Use 't.Error' or 't.Fatal' to report test failures clearly.
Run tests using the 'go test' command in your project directory.
Naming and file placement are crucial for tests to run automatically.