Section 10 of 12

Testing in Go

Write unit tests and test your code effectively

Course Progress

Section 10 of 12

83% complete

Tutorials

Unit Testing

Go includes testing in the standard library. Testing functions start with Test and receive *testing.T.

Code Examples

Basic Testgo
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)
    }
}

func TestAddZero(t *testing.T) {
    result := Add(0, 0)
    if result != 0 {
        t.Fail()
    }
}
Table-Driven Testsgo
package main

import "testing"

func TestAddMultiple(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"positive numbers", 2, 3, 5},
        {"negative numbers", -1, -1, -2},
        {"mixed", 5, -3, 2},
        {"zeros", 0, 0, 0},
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            result := Add(tt.a, tt.b)
            if result != tt.expected {
                t.Errorf("got %d, want %d", result, tt.expected)
            }
        })
    }
}

Exercises

Test a Calculator

Write unit tests for calculator functions

INTERMEDIATE

Starter Code:

package main

import "testing"

func Add(a, b int) int { return a + b }
func Subtract(a, b int) int { return a - b }
func Multiply(a, b int) int { return a * b }

// TODO: Write tests for all functions

Hands-on Project

Comprehensive Test Suite

Write comprehensive tests for a utility library

ADVANCED

Learning Objectives

  • >Write effective tests
  • >Use table-driven tests
  • >Achieve high coverage

Project Tips

  • > Start by understanding the requirements
  • > Break the project into smaller tasks
  • > Test your code frequently as you build
  • > Add error handling throughout your code
  • > Consider edge cases and validate inputs
  • > Document your code with comments