Testing is an essential part of any software development process. It ensures that the code is working correctly and meeting the requirements. Go is a language that has testing built-in as a first-class citizen, which makes testing Go programs easy and efficient. In this tutorial, we will explore the basics of writing tests for Go programs.


Getting started

To write tests in Go, we create a separate file with the same name as the file we want to test, but with the suffix "_test". For example, if we want to test the file "main.go", we create a file named "main_test.go". This file will contain our test functions.


Test Functions

Test functions in Go must have a name starting with "Test" followed by a descriptive name. For example, "TestAddition" would be a good name for a test function that tests the addition operation.


Test functions have the following signature:

func TestXxx(*testing.T)

The "Xxx" part of the name can be any string, but it should start with a capital letter. The "testing.T" parameter is a pointer to a testing object that we use to report the results of our tests.

Here's an example of a simple test function:

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

The "t.Errorf" function is used to report an error if the test fails. In this case, we're reporting that the addition function returned an incorrect result.


Table-Driven Tests

Go provides a convenient way to run multiple test cases for the same function using table-driven tests. In this type of test, we define a slice of structs, where each struct represents a test case. Here's an example:

func TestAdditionTable(t *testing.T) {
    tests := []struct {
        a, b, expected int
    }{
        {2, 3, 5},
        {0, 0, 0},
        {-1, 1, 0},
        {10, -5, 5},
    }

    for _, tt := range tests {
        result := add(tt.a, tt.b)
        if result != tt.expected {
            t.Errorf("Expected %d, but got %d for %d + %d", tt.expected, result, tt.a, tt.b)
        }
    }
}


The "for" loop iterates over the test cases, and the "t.Errorf" function reports an error for each case that fails.


Running Tests

To run the tests for our program, we use the "go test" command in the terminal. It will automatically discover and run all the test functions in our program. By default, it will display a summary of the test results, including the number of tests run, the number of failures, and the time taken.


Conclusion

Testing is an essential part of writing robust software. Go makes testing easy and efficient, thanks to its built-in testing framework. In this tutorial, we covered the basics of writing tests for Go programs, including test functions, table-driven tests, and running tests. With this knowledge, you can start writing tests for your Go programs and ensure their correctness and stability.