#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Testing

Testing in Go – Writing Unit Tests and Benchmarks (Table-Driven)

Writing a Basic Test

Go's built-in testing package requires test files to end in _test.go and test functions to start with Test.

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

Table-Driven Tests

A common Go idiom for testing multiple input/output combinations concisely.

func TestAddTable(t *testing.T) {
    cases := []struct {
        a, b, expected int
    }{
        {1, 2, 3},
        {5, 5, 10},
        {-1, 1, 0},
    }
    for _, c := range cases {
        result := Add(c.a, c.b)
        if result != c.expected {
            t.Errorf("Add(%d, %d) = %d; want %d", c.a, c.b, result, c.expected)
        }
    }
}

Writing Benchmarks

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

Run tests with go test and benchmarks with go test -bench=.

Ready to master real-world Go skills?

Learn Go hands-on with mentor-led, live sessions.

Explore Course