Testing
Testing in Go is an integral part of the development process. The Go programming language comes with a built-in testing framework that makes it easy to write and run tests.
Suppose you have a simple function that adds two numbers in a file named calculator.go
:
// calculator.go
package calculator
// Add returns the sum of two integers
func Add(a, b int) int {
return a + b
}
Now, create a test file named calculator_test.go
in the same directory to test the Add function:
// calculator_test.go
package calculator
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
expected := 5
if result != expected {
t.Errorf("Add(2, 3) = %d; expected %d", result, expected)
}
}
Test functions must be in files ending with _test.go
and have a name starting with Test
.
To run the tests, use the go test
command:
go test
Benchmarking
Benchmarking is a process of measuring the performance of functions or pieces of code.
// calculator.go
package calculator
// Factorial calculates the factorial of n
func Factorial(n int) int {
if n <= 1 {
return 1
}
return n * Factorial(n-1)
}
// calculator_benchmark_test.go
package calculator
import (
"testing"
)
func BenchmarkFactorial(b *testing.B) {
for i := 0; i < b.N; i++ {
Factorial(10) // Replace 10 with the value you want to benchmark
}
}
BenchmarkFactorial
is the benchmark function. The b.N
loop runs the code inside the loop repeatedly to measure its performance.
To run the benchmark, use the go test
command with the -bench
flag:
go test -bench .
Output will include the time taken for each iteration and the number of operations per second. Benchmark results can help you identify performance bottlenecks and optimize your code.