Testing Go Code

Go has testing built-in to the language’s core libraries.

Set up test file

Start by making a new file in the same literal folder as our source code, named hyphenate-spaces_test.go:

> cd $GOPATH/src/bitbucket.org/theandruu/go-public/learning/stringutil
> touch hyphenate-spaces_test.go

And enter the following content:


package stringutil

import "testing"

func TestHyphenateSpaces(t *testing.T) {
    cases := []struct {
        in, want string
    }{
        {"Hello world", "Hello-world"},
        {"Hello 世界", "Hello-世界"},
        {"", ""},
    }
    for _, c := range cases {
        got := HyphenateSpaces(c.in)
        if got != c.want {
            t.Errorf("HyphenateSpaces(%q) == %q, want %q", c.in, got, c.want)
        }
    }
}

Running tests

The tests can be executed either by running go test from the directory containing the source code, or anywhere on the filesystem with:


> go test bitbucket.org/theandruu/go-public/learning/stringutil
ok      bitbucket.org/theandruu/go-public/learning/stringutil  0.001s

Ta-daa! Got our first test under our belt.

Testing guidelines

◀   Organizing Go Code Sharing code   ▶