0
0
Goprogramming~5 mins

Testing package overview in Go

Choose your learning style9 modes available
Introduction

Testing helps you check if your Go code works correctly. The testing package makes it easy to write and run tests.

When you want to check if a function returns the right result.
When you fix a bug and want to make sure it stays fixed.
When you add new features and want to confirm they work well.
When you want to run tests automatically before sharing your code.
Syntax
Go
func TestXxx(t *testing.T) {
    // test code here
}

Test functions start with 'Test' and take *testing.T as a parameter.

Use t.Error or t.Fatal to report test failures.

Examples
This test checks if Add(2, 3) returns 5.
Go
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Error("Expected 5")
    }
}
This test checks if dividing by zero returns an error.
Go
func TestDivide(t *testing.T) {
    _, err := Divide(4, 0)
    if err == nil {
        t.Fatal("Expected error for division by zero")
    }
}
Sample Program

This program defines a simple Add function and a test to check it returns the correct sum.

Go
package main

import (
    "testing"
)

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

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Error("Add(2, 3) should be 5")
    }
}
OutputSuccess
Important Notes

Run tests using go test in the terminal.

Test files must end with _test.go to be recognized.

Use t.Error to report errors but continue, t.Fatal to stop the test immediately.

Summary

The testing package helps you write tests as functions starting with Test.

Tests check if your code works as expected and report problems.

Run tests easily with go test command.