The testing package

The testing package provides a framework for writing and running tests. The testing package is part of the standard library and is designed to be simple and easy to use.

Test Functions conventions:

  • Test functions are regular Go functions, by convention, they start with a name starting with Test
  • Test functions take one argument, usually of type *testing.T.
  • Example test function
package mypackage

import (
    "testing"
)

func TestAdd(t *testing.T) {
    result := add(2, 3)
    expected := 5

    if result != expected {
        t.Errorf("Expected %d, but got %d", expected, result)
    }
}

Test Execution:

  • To run tests, you can use the go test command followed by the package path.
  • Example:
go test mypackage
  • The testing package automatically discovers and runs all test functions in the package.

The TestMain function

  • TestMain is a special function that can be included in a test file
  • TestMain runs before any tests in the file and can be used to set up test-specific configurations or perform actions before and after all tests in the file are executed.
  • *testing.M provides methods like Run to run tests explicitly and control the execution flow.
  • Example:
package mypackage

import (
    "testing"
)

func TestMain(m *testing.M) {
    // Set up test environment

    // Run the tests
    exitCode := m.Run()

    // Clean up test environment

    // Exit with the appropriate code
    os.Exit(exitCode)
}

func TestExample(t *testing.T) {
    // Test logic here
}

In summary, *testing.T is used within test functions to report failures and log information, while *testing.M is used in the TestMain function to control the execution of tests and set up/clean up test environments