0
0
GoHow-ToBeginner · 3 min read

How to Run Tests in Go: Simple Guide with Examples

To run tests in Go, write test functions in files ending with _test.go using the testing package, then run go test in your terminal inside the package directory. This command automatically finds and runs all test functions starting with Test.
📐

Syntax

In Go, test functions must be named starting with Test and take a single parameter of type *testing.T. Test files must end with _test.go. Use go test command to run all tests in the current directory.

  • Test function: Must start with Test and accept t *testing.T
  • Test file: Named with _test.go suffix
  • Run tests: Use go test in terminal
go
func TestExample(t *testing.T) {
    // test code here
}
💻

Example

This example shows a simple function and its test. The test checks if the function returns the expected result. Running go test will execute the test and report success or failure.

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)
    }
}
Output
PASS ok command-line-arguments 0.001s
⚠️

Common Pitfalls

Common mistakes include naming test functions incorrectly, forgetting the _test.go suffix on test files, or not importing the testing package. Also, tests must be in the same package or a _test package to run properly.

Wrong test function name example:

go
func testAdd(t *testing.T) { // wrong: should be TestAdd
    // test code
}

// Correct:
func TestAdd(t *testing.T) {
    // test code
}
📊

Quick Reference

  • Test function name: Must start with Test
  • Test file name: Must end with _test.go
  • Run tests: Use go test in terminal
  • Fail test: Use t.Errorf or t.Fatal
  • Run specific test: go test -run TestName

Key Takeaways

Write test functions starting with Test and accept *testing.T parameter.
Name test files with _test.go suffix to be recognized by Go.
Run tests using the go test command in the package directory.
Use t.Errorf or t.Fatal inside tests to report failures.
Use go test -run to run specific tests by name.