Filename being [name]_test.go
package yourpackage
import (
"testing"
)
// all the functions
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`
}
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()
}
}
func BenchmarkBigLen(b *testing.B) {
doSetup()
b.ResetTimer()
for i := 0; i < b.N; i++ {
myFunction()
}
}
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()
}
}
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