Skip to main content
Go Language Fundamentals for Beginners to Advanced
CHAPTER 26 Beginner

Testing in Go

Updated: May 17, 2026
5 min read

# CHAPTER 26

Testing in Go

1. Introduction

In many languages, writing tests requires downloading massive testing frameworks like Jest (JS) or JUnit (Java). Go treats testing as a first-class citizen. The Go compiler has a built-in testing framework via the testing package and the go test command. Writing reliable, automatically tested code is a non-negotiable skill for modern backend engineers.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Name and structure Go test files.
  • Write basic Unit Tests.
  • Run tests using the go test command.
  • Implement Table-Driven Tests (the Go community standard).
  • Write Benchmark Tests to measure performance.

3. File Naming and Structure

To write a test for a Go file, you create a new file ending in test.go. For example, if you have a file named math.go, your test file MUST be named mathtest.go.

When you compile your application for production (go build), the compiler automatically ignores all _test.go files, keeping your production binary incredibly small!

4. Writing Your First Unit Test

Let's test a simple addition function.

math.go

go
12345
package main

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

math_test.go

go
123456789101112131415
package main

import "testing"

// Test functions MUST start with the word 'Test' followed by a capital letter.
// They MUST accept a pointer to testing.T
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5

    if result != expected {
        // t.Errorf logs the failure and marks the test as FAILED
        t.Errorf("Add(2, 3) FAILED. Expected %d, got %d", expected, result)
    }
}

5. Running Tests

Open your terminal in the folder containing these files and run:
bash
1
go test

*Output:* PASS ok my-app 0.001s

To get verbose, detailed output of every single test, run:

bash
1
go test -v

6. Table-Driven Tests (The Go Standard)

If you want to test Add(0, 0), Add(-5, 10), and Add(100, 200), writing 10 separate Test functions is repetitive. The Go community solved this with Table-Driven Tests. You create a slice of anonymous structs containing your inputs and expected outputs, and loop through them.
go
1234567891011121314151617181920212223
func TestAddTableDriven(t *testing.T) {
    // 1. Define the "Table" of test cases
    tests := []struct {
        name     string
        a        int
        b        int
        expected int
    }{
        {"Positive Numbers", 2, 3, 5},
        {"Negative Numbers", -5, -2, -7},
        {"Zeroes", 0, 0, 0},
    }

    // 2. Loop through and execute
    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            result := Add(tc.a, tc.b)
            if result != tc.expected {
                t.Errorf("Expected %d, got %d", tc.expected, result)
            }
        })
    }
}

7. Benchmark Tests

Is your algorithm fast? Go can automatically measure how many nanoseconds it takes your code to run. Benchmark tests start with Benchmark and accept a pointer to testing.B.
go
12345678
// Benchmark functions test performance
func BenchmarkAdd(b *testing.B) {
    // b.N is automatically adjusted by Go to run the loop millions of times
    // until it gets a statistically accurate time measurement.
    for i := 0; i < b.N; i++ {
        Add(100, 200)
    }
}

Run benchmarks in the terminal using:

bash
1
go test -bench=.

*Output Example:* BenchmarkAdd-8 1000000000 0.314 ns/op (Meaning it ran 1 Billion times, and took 0.314 nanoseconds per operation!)

8. Common Mistakes

  • Wrong Function Names: Naming your test testAdd() (lowercase 't') or Testadd() (lowercase second word). The function MUST start with Test followed by a Capital letter. If it doesn't, go test completely ignores it.
  • Not using Table-Driven Tests: Writing 50 blocks of copy-pasted if result != expected code. It makes tests unreadable and hard to maintain.

9. Best Practices

  • Test Coverage: You can check what percentage of your code is covered by tests using: go test -cover. Aim for 70-80% coverage in enterprise applications.

10. Exercises

  1. 1. Write a function IsEven(n int) bool in main.go.
  1. 2. Create maintest.go and write a standard unit test to verify IsEven(4) returns true.
  1. 3. Write a Table-Driven test to check 2, 3, 0, and -4.

11. MCQs with Answers & Explanations

Question 1

What must a Go test file be named?

Question 2

What terminal command executes all tests in the current directory?

Question 3

What must a Unit Test function name start with?

Question 4

What parameter must be passed into a standard Unit Test function?

Question 5

How do you mark a test as failed and print an error message?

Q6. Do test.go files get compiled into the final production binary? a) Yes, making the file bigger b) No, the compiler ignores them for production builds Answer: b) No, the compiler ignores them.
Question 7

What is a Table-Driven test?

Question 8

What parameter must be passed into a Benchmark Test function?

Question 9

What does the b.N represent in a Benchmark loop?

Question 10

How do you check what percentage of your code is tested?

12. Interview Preparation

Interview Questions:
  1. 1. Describe the structure and benefits of a Table-Driven Test in Go.
  1. 2. How do you ensure that test files do not bloat the production binary size? (Answer: By adhering to the test.go naming convention, the compiler handles it automatically).
  1. 3. How do you measure the nanosecond performance of a specific function in Go?

13. Summary

Testing in Go is frictionless. Because the testing package and go test commands are built-in, there are no external dependencies to configure. Table-Driven tests keep scenarios organized, and Benchmark tests provide deep insights into performance, ensuring your high-speed backend code remains flawless.

14. Next Chapter Recommendation

We have covered the syntax, the web, the database, and testing. In Chapter 27: Go Data Structures and Algorithms, we will review how to implement foundational Computer Science concepts (like Linked Lists and Queues) utilizing Go's unique features like Pointers and Slices.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·