0
0
Goprogramming~5 mins

Writing basic test functions in Go

Choose your learning style9 modes available
Introduction

Tests help check if your code works correctly. Writing basic test functions lets you find mistakes early and fix them easily.

When you want to check if a function returns the right answer.
When you change code and want to make sure nothing else breaks.
When you want to share your code and prove it works.
When you want to automate checking many parts of your program.
When you want to learn how your code behaves with different inputs.
Syntax
Go
func TestFunctionName(t *testing.T) {
    // test code here
}

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

Use t.Error or t.Fail to mark a test as failed.

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.Error("Expected 5, got", result)
    }
}
This test checks if IsEven correctly identifies even and odd numbers.
Go
func TestIsEven(t *testing.T) {
    if !IsEven(4) {
        t.Error("4 should be even")
    }
    if IsEven(3) {
        t.Error("3 should not be even")
    }
}
Sample Program

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

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("Expected 5, got", result)
    }
}
OutputSuccess
Important Notes

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

Run tests using go test command in the terminal.

Tests should be simple and check one thing at a time.

Summary

Basic test functions start with Test and use *testing.T.

Use t.Error to report failures inside tests.

Run tests with go test to check your code automatically.