Lesson 8 • Advanced

    Testing in Go 🐹

    Write unit tests, table-driven tests, benchmarks, and HTTP handler tests using Go's built-in testing framework — no external libraries needed.

    What You'll Learn in This Lesson

    • • Go's built-in testing package and conventions
    • • Table-driven tests — Go's signature testing pattern
    • • Benchmarks and memory profiling
    • • Testing HTTP handlers with httptest
    • • Test helpers, TestMain, and coverage

    1️⃣ Test Basics

    Go's testing framework is built right into the language. Test files end with _test.go, test functions start with Test, and you run them with go test.

    Try It: Test Basics

    Write and run your first Go test

    Try it Yourself »
    JavaScript
    // Testing in Go — Built-in Framework
    console.log("=== Go Testing Conventions ===");
    console.log("Go has a built-in testing framework — no external library needed!");
    console.log();
    console.log("Rules:");
    console.log("  • Test files end with _test.go");
    console.log("  • Test functions start with Test");
    console.log("  • Accept *testing.T parameter");
    console.log("  • Same package as code being tested");
    console.log();
    
    console.log("=== Example ===");
    console.log("// math.go");
    console.log("func 
    ...

    2️⃣ Table-Driven Tests

    Table-driven tests are Go's most iconic testing pattern. Define test cases as data in a slice, then loop through them with subtests. This makes adding new cases trivial.

    Try It: Table-Driven Tests

    The most common Go testing pattern

    Try it Yourself »
    JavaScript
    // Table-Driven Tests — Go's Signature Pattern
    console.log("=== Table-Driven Tests ===");
    console.log("The most common testing pattern in Go.");
    console.log("Define test cases as data, loop through them.");
    console.log();
    
    console.log("func TestAdd(t *testing.T) {");
    console.log("    tests := []struct {");
    console.log("        name     string");
    console.log("        a, b     int");
    console.log("        expected int");
    console.log("    }{");
    console.log('        {"positive", 2, 3, 5},');
    console.
    ...

    3️⃣ Benchmarks & Helpers

    Benchmarks measure performance with nanosecond precision. Test helpers reduce duplication. TestMain provides setup and teardown hooks for the entire test suite.

    Try It: Benchmarks

    Performance benchmarks, helpers, and TestMain

    Try it Yourself »
    JavaScript
    // Benchmarks & Test Helpers
    console.log("=== Benchmarks ===");
    console.log("Measure performance with the testing framework.");
    console.log();
    console.log("func BenchmarkAdd(b *testing.B) {");
    console.log("    for i := 0; i < b.N; i++ {");
    console.log("        Add(2, 3)");
    console.log("    }");
    console.log("}");
    console.log();
    console.log("  $ go test -bench=.");
    console.log("  BenchmarkAdd-8    1000000000    0.26 ns/op");
    console.log("  → 1 billion iterations, 0.26 nanoseconds each");
    console.l
    ...

    4️⃣ Testing HTTP Handlers

    The httptest package lets you test HTTP handlers without starting a real server. Create a request, record the response, and assert on status codes and body content.

    Try It: HTTP Tests

    Test REST API handlers with httptest

    Try it Yourself »
    JavaScript
    // Testing HTTP Handlers
    console.log("=== httptest Package ===");
    console.log("Go provides httptest for testing HTTP handlers without a real server.");
    console.log();
    
    console.log("func TestGetUsersHandler(t *testing.T) {");
    console.log("    // Create a request");
    console.log('    req := httptest.NewRequest("GET", "/api/users", nil)');
    console.log("    // Create a response recorder");
    console.log("    w := httptest.NewRecorder()");
    console.log();
    console.log("    // Call the handler");
    console.l
    ...

    ⚠️ Common Mistakes

    ⚠️
    Not using t.Helper() — Without it, error messages point to your helper function instead of the actual failing test.
    ⚠️
    Testing implementation, not behavior — Test the public API. Internal details should be free to change without breaking tests.
    💡
    Pro Tip: Run go test -race ./... in CI. It detects data races that only manifest under concurrent load.

    📋 Quick Reference — Go Skills Mastered

    LessonKey Skills
    1. IntroSetup, syntax, fmt package
    2. VariablesTypes, slices, maps, control flow
    3. FunctionsMulti-return, closures, defer
    4. StructsStructs, interfaces, pointers
    5. ConcurrencyGoroutines, channels, select
    6. ErrorsError values, wrapping, Is/As
    7. WebHTTP servers, REST, middleware
    8. TestingTable-driven, benchmarks, httptest

    🎉 Course Complete!

    Congratulations! You've completed the entire Go course. You can now build, test, and deploy production Go applications — from concurrent services to REST APIs. Consider exploring Go modules, database integration, or Docker deployments next!

    Sign up for free to track which lessons you've completed and get learning reminders.

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service