Exercise 5: Writing Unit Tests in Go

Learn how to test your functions and ensure their correctness.

Why Write Unit Tests?

Unit tests ensure that each part of your code works correctly and prevents regressions during updates.

Writing a Test Using the `testing` Package

Go includes the built-in `testing` package for writing and executing unit tests.

package main

import (
    "testing"
)

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

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

Running Tests

Tests can be executed with the command:

go test

Exercise Instructions

  • Create a file named maths.go containing a function `Multiplication`.
  • Create a file named maths_test.go to test this function.
  • Write unit tests to validate the function's correctness.
  • Run your tests using `go test`.

Exercise Solution

package main

import (
    "testing"
)

func Multiplication(a, b int) int {
    return a * b
}

func TestMultiplication(t *testing.T) {
    result := Multiplication(4, 5)
    expected := 20
    if result != expected {
        t.Errorf("Error: got %d, expected %d", result, expected)
    }
}

Best Practices & Common Errors

  • ✅ Always test edge cases and expected errors.
  • ✅ Use `t.Run` to organize tests into sub-tests.
  • ✅ Automate test execution in a CI/CD pipeline.
  • ⚠️ Never ignore errors or unexpected results.

📚 Learn more about testing in Go:

Read the Official Documentation ← Previous Exercise Next Exercise →

🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee