0
0
Goprogramming~5 mins

Running tests in Go

Choose your learning style9 modes available
Introduction

Running tests helps you check if your code works correctly. It finds mistakes early so you can fix them quickly.

You want to make sure a new feature works before sharing your program.
You changed some code and want to confirm nothing else broke.
You want to automatically check your program every time you save changes.
You want to share your code with others and prove it works.
You want to catch bugs before users find them.
Syntax
Go
func TestFunctionName(t *testing.T) {
    // test code here
}

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

Use go test command to run all tests in a package.

Examples
This test checks if the Add function returns 5 when adding 2 and 3.
Go
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Expected 5, got %d", result)
    }
}
This test checks if the IsEven function correctly identifies 4 as even.
Go
func TestIsEven(t *testing.T) {
    if !IsEven(4) {
        t.Error("4 should be even")
    }
}
Sample Program

This program defines a simple Add function and a test TestAdd that checks if adding 2 and 3 equals 5.

Run go test in the terminal to see the test result.

Go
package main

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

// To run tests, place the following test function in a separate file named add_test.go
// and run 'go test' in the terminal.

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Expected 5, got %d", result)
    }
}
OutputSuccess
Important Notes

Test files must be named with _test.go suffix to be recognized by go test.

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

Tests help keep your code reliable and easier to maintain.

Summary

Tests check if your code works as expected.

Write test functions starting with Test and use go test to run them.

Fix problems early by running tests often.