Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 11 of 60 · Go

Testing in Go: The `testing` Package

Duration: 20 minutes

Testing in Go: The testing Package

Testing is built into Go. This lesson explains how to write unit tests, run them, and use table-driven patterns.

Unit testing

Create a file ending in _test.go and use the testing package.

package main

import "testing"

func TestAdd(t *testing.T) {
    got := add(2, 3)
    want := 5
    if got != want {
        t.Fatalf("add(2,3) = %d; want %d", got, want)
    }
}

Run tests with:

go test ./... -v

Table-driven tests

Use a slice of cases to test many inputs with the same logic.

func TestIsEven(t *testing.T) {
    cases := []struct{ in int; want bool }{{2,true},{3,false},{0,true}}
    for _, c := range cases {
        if got := isEven(c.in); got != c.want {
            t.Errorf("isEven(%d) = %v; want %v", c.in, got, c.want)
        }
    }
}

Benchmarks

Benchmark code measures performance and runs repeatedly.

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

Info

Use t.Parallel() only when test code is safe to run concurrently, and avoid race conditions inside tests.

Previous: Working with Files & I/ONext: Benchmarking & Profiling