How to run a specific test in Go
Go provides the go test
command for running the unit tests in a project.
Running this command will ordinarily run the whole test suite, but you can limit
it to only a specific file or test.
Let’s assume you have the following main.go
file:
package main
import "fmt"
func square(num int) int {
return num * num
}
func factorial(num int) int {
if num == 0 {
return 1
}
return num * factorial(num-1)
}
func main() {
fmt.Println(square(10))
fmt.Println(factorial(5))
}
And tests for the main
package defined in a main_test.go
file as follows:
package main
import "testing"
func TestSquare(t *testing.T) {
tests := []struct {
number int
want int
}{
{number: 10, want: 100},
{number: 5, want: 25},
{number: 7, want: 49},
}
for i, tc := range tests {
result := square(tc.number)
if result != tc.want {
t.Fatalf("Test %d failed — Expected %d, got %d", i+1, tc.want, result)
}
}
}
func TestFactorial(t *testing.T) {
tests := []struct {
number int
want int
}{
{number: 9, want: 362880},
{number: 5, want: 120},
{number: 0, want: 1},
}
for i, tc := range tests {
result := factorial(tc.number)
if result != tc.want {
t.Fatalf("Test %d failed — Expected %d, got %d", i+1, tc.want, result)
}
}
}
If you run go test
, it will run both the TestFactorial
and TestSquare
functions.
$ go test -v
=== RUN TestSquare
--- PASS: TestSquare (0.00s)
=== RUN TestFactorial
--- PASS: TestFactorial (0.00s)
PASS
ok github.com/ayoisaiah/example 0.002s
To run a specific one, pass the name of the test to the -run
flag as shown
below:
$ go test -v -run TestSquare
=== RUN TestSquare
--- PASS: TestSquare (0.00s)
PASS
ok github.com/ayoisaiah/example 0.002s
Be sure to check the documentation for more information.