Testing and benchmarking in Go

Go: Testing and benchmarking:

Golang has built-in support for testing and benchmarking code. Understanding how to write effective tests and benchmarks is essential for creating high-quality, performant applications.

Testing in Go

Go provides a built-in testing framework that makes it easy to write tests for your code. To write tests in Go, create a file ending in _test.go that contains test functions with names starting with Test.

  • Example of a test function:
    func TestAdd(t *testing.T) {
        result := Add(2, 3)
        expected := 5
        if result != expected {
            t.Errorf("Add(2, 3) = %d, expected %d", result, expected)
        }
    }

This code defines a test function TestAdd that calls a function Add with arguments 2 and 3 and checks that the result is 5 using the t.Errorf function. If the test fails, it prints an error message to the console.

To run tests in Go, use the go test command in the terminal at the root of your project directory. By default, go test will run all the tests in your project. You can also specify a package, directory, or file to test with go test <package/directory/file>.

Benchmarking in Go Go also provides a built-in benchmarking framework that makes it easy to benchmark your code. To write benchmarks in Go, create a file ending in _test.go that contains benchmark functions with names starting with Benchmark.

  • Example of a benchmark function:
    func BenchmarkAdd(b *testing.B) {
        for i := 0; i < b.N; i++ {
            Add(2, 3)
        }
    }

This code defines a benchmark function BenchmarkAdd that calls a function Add with arguments 2 and 3 in a loop for b.N iterations. The b.N parameter is automatically set by the testing framework to a value that makes it possible to measure the performance of the function.

To run benchmarks in Go, use the go test -bench command in the terminal at the root of your project directory. By default, go test -bench will run all the benchmarks in your project. You can also specify a package, directory, or file to benchmark with go test -bench <package/directory/file>.

I hope that helps you get started with testing and benchmarking in Go! Let me know if you have any more questions.

Previous Article

Next Article