Unit Testing with testing in Go - Golang (Because Bugs Hate Tests!)

Unit testing in Go is like giving your code a health check-up—you make sure everything is running smoothly before releasing it into the wild!  Let's explore Go’s built-in testing package and learn how to write tests like a pro.

Why Test? (Because Debugging is Painful!)

  • Catch bugs early before they cause chaos.
  • Ensure code reliability when making changes.
  • Gain confidence that your program won’t explode.

Writing Your First Test (Hello, testing!)

Go provides a simple yet powerful testing package. Test functions must:

  • Live in a file ending with _test.go (e.g., math_test.go).
  • Start with Test and take a *testing.T parameter.

Example:

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("Expected %d, got %d", expected, result)
    }
}

Run tests using:

go test

If all goes well, you’ll see PASS!

Table-Driven Tests (Efficient and Scalable!)

Instead of writing multiple if checks, use a table-driven approach:

func TestAddTableDriven(t *testing.T) {
    tests := []struct {
        a, b, expected int
    }{
        {1, 1, 2},
        {2, 2, 4},
        {10, 5, 15},
    }
    
    for _, tt := range tests {
        result := Add(tt.a, tt.b)
        if result != tt.expected {
            t.Errorf("For %d + %d, expected %d but got %d", tt.a, tt.b, tt.expected, result)
        }
    }
}

Why use table-driven tests? They’re clean, reusable, and scalable!

Benchmarking (Speed Matters!)

Want to see if your code runs like a cheetah or a snail?  Use benchmarking!

func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(100, 200)
    }
}

Run benchmarks with:

go test -bench .

Check the execution time and optimize accordingly!

Mocking (Because Not Everything is Test-Friendly!)

Sometimes, you need to fake dependencies. Use interfaces and mock implementations to test components in isolation.

Example:

type Database interface {
    GetUser(id int) string
}

type MockDB struct{}

func (m MockDB) GetUser(id int) string {
    return "John Doe"
}

 Replace actual dependencies with mocks for isolated unit tests.

Testing in Go is fast, built-in, and essential for writing robust programs. Now go forth and break your code safely before it breaks in production!

Post a Comment

0 Comments