0
0
Goprogramming~5 mins

Test-driven basics in Go

Choose your learning style9 modes available
Introduction

Test-driven basics help you write code that works right the first time. You write tests before the code to check if it does what you want.

When you want to make sure your code does exactly what you expect.
When you want to catch mistakes early before running the full program.
When you want to add new features safely without breaking old ones.
When you want to understand the requirements clearly before coding.
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.Fatal to report test failures.

Examples
This test checks if the Add function returns 5 when adding 2 and 3.
Go
func TestAdd(t *testing.T) {
    got := Add(2, 3)
    want := 5
    if got != want {
        t.Errorf("Add(2, 3) = %d; want %d", got, want)
    }
}
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(5) {
        t.Error("5 should not be even")
    }
}
Sample Program

This program defines a simple Add function.

You run the test using go test command in the terminal.

Go
package main

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

// To run this test, save the test code in a separate file named add_test.go
// and run: go test
OutputSuccess
Important Notes

Test files in Go end with _test.go and are separate from main code files.

Run tests with go test in the terminal inside your project folder.

Tests help you find bugs early and keep your code working as you add features.

Summary

Write tests before or alongside your code to check it works.

Test functions start with Test and use *testing.T to report errors.

Run tests with go test to see if your code passes or fails.