0
0
GoHow-ToBeginner · 3 min read

How to Use Testing Package in Go for Simple Unit Tests

Use the testing package in Go by creating functions starting with Test that accept *testing.T as a parameter. Run tests with go test command, which automatically finds and executes these test functions.
📐

Syntax

In Go, test functions must start with Test and take a single parameter of type *testing.T. Use methods on testing.T to report failures.

  • func TestXxx(t *testing.T): Defines a test function.
  • t.Error / t.Errorf: Marks test as failed but continues.
  • t.Fatal / t.Fatalf: Marks test as failed and stops execution.
go
func TestExample(t *testing.T) {
    // test code here
    if 1+1 != 2 {
        t.Error("Math is broken")
    }
}
💻

Example

This example shows a simple test for a function that adds two numbers. It demonstrates how to write a test function and use t.Errorf to report errors.

go
package main

import "testing"

func Add(a, b int) int {
    return a + b
}

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5
    if result != expected {
        t.Errorf("Add(2, 3) = %d; want %d", result, expected)
    }
}
Output
PASS ok command-line-arguments 0.001s
⚠️

Common Pitfalls

Common mistakes when using the testing package include:

  • Not naming test functions starting with Test, so go test won't find them.
  • Forgetting to import testing package.
  • Using t.Error when you want to stop the test immediately, instead of t.Fatal.
  • Writing tests in the main package instead of a separate package or file ending with _test.go.
go
/* Wrong: function name does not start with Test */
func addTest(t *testing.T) {
    t.Error("This won't run automatically")
}

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

Quick Reference

Here is a quick summary of key points when using the testing package:

ConceptDescription
Test function nameMust start with 'Test' and take '*testing.T' parameter
Run testsUse 'go test' command in terminal
Fail testUse 't.Error' or 't.Errorf' to mark failure but continue
Stop testUse 't.Fatal' or 't.Fatalf' to fail and stop immediately
Test filesMust be named with '_test.go' suffix

Key Takeaways

Test functions must start with 'Test' and accept '*testing.T' as parameter.
Use 'go test' command to run all tests in your package automatically.
Use 't.Error' to report failure and continue, 't.Fatal' to stop test immediately.
Name test files with '_test.go' suffix for Go to recognize them as tests.
Always import the 'testing' package to write test functions.