Skip to content

Instantly share code, notes, and snippets.

@nelsestu
Forked from thehowl/cheatsheet.md
Last active August 8, 2021 23:45
Show Gist options
  • Save nelsestu/ab00f108b8f6ed872d8734776a75c23b to your computer and use it in GitHub Desktop.
Save nelsestu/ab00f108b8f6ed872d8734776a75c23b to your computer and use it in GitHub Desktop.
Go `testing` package cheatsheet

Basic file

Filename being [name]_test.go

package yourpackage

import (
	"testing"
)

// all the functions

Writing a test

func TestMyFunction(t *testing.T) {
	output, err := myFunction()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("%+v", output) // will only be printed with `go test -v`
}

Writing a benchmark

Benchmarks are only executed when the -bench flag is given.

func BenchmarkMyFunction(b *testing.B) {
    for i := 0; i < b.N; i++ {
    	// actual code to execute lies here
        myFunction()
    }
}

Writing a benchmark with expensive operations

func BenchmarkBigLen(b *testing.B) {
    doSetup()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        myFunction()
    }
}

Skipping a test (or benchmark)

var run bool

func TestMyFunction(t *testing.T) {
	if !run {
		t.Skip("run is false. Skipping test") // you can also skip directly using t.SkipNow()
	}
}

Writing examples

Examples are actually tests. The // Output: comment will be used, when running go test, to the determine that the function does what it should.

func ExamplePrintf() {
	fmt.Printf("%d\n", 1337)
	// Output: 1337
}

For examples to be associated with stuff in godoc:

func ExampleFoo()     // documents the Foo function or type
func ExampleBar_Qux() // documents the Qux method of type Bar
func Example()        // documents the package as a whole
func Example_moar()   // documents the package as a whole again, with one further example
                      // (must be in format `Xxx_xxx`). Works with all of the above

More

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment