How to Run a Single Test

· 228 words · 2 minutes read

Go has a simple command line for running its tests, with go test. However, often when writing tests you don’t care about the rest of the test suite - you just want to run your new test. This post shows you the command you need to run just your test, as well as a full example below.

TL;DR: use -run

go test -run TestSub

Example:

main.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import "fmt"

func main() {
    fmt.Printf("add: %d\n", add(2, 6))
    fmt.Printf("sub: %d\n", sub(2, 6))
}

func add(num1 int, num2 int) int {
    return num1 + num2
}

func sub(num1 int, num2 int) int {
    return num1 - num2
}

main_test.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import "testing"

func TestAdd(t *testing.T) {
    result := add(2, 4)
    expected := 6
    if result != expected {
        t.Errorf("add() test returned an unexpected result: got %v want %v", result, expected)
    }
}

func TestSub(t *testing.T) {
    result := sub(2, 4)
    expected := -2
    if result != expected {
        t.Errorf("sub() test returned an unexpected result: got %v want %v", result, expected)
    }
}

Command: (We are running with the -v parameter so we can see which tests have been run.)

go test -v -run TestSub

running a single golang test

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!