Go by Example: Testing and Benchmarking

In Go, testing and benchmarking of code is done through the use of the testing package.

Here’s an example of how to write tests for a function:

package main

import (
  "testing"
)

func TestAddition(t *testing.T) {
  expected := 4
  result := add(2, 2)

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

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

In this example, the TestAddition function tests the add function. The t *testing.T argument to the test function provides methods for testing and reporting errors. The t.Errorf method is called if the expected result does not match the actual result.

Here’s an example of how to write benchmarks for a function:

package main

import (
  "testing"
)

func BenchmarkAddition(b *testing.B) {
  for i := 0; i < b.N; i++ {
    add(2, 2)
  }
}

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

In this example, the BenchmarkAddition function benchmarks the add function. The b *testing.T argument to the benchmark function provides methods for benchmarking. The b.N field is the number of times the function will be run, and the function should aim to run as quickly as possible.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *