[Golang] Write Example Code in Testing


Demonstrate the usage of your methods by writing example code in the testing of your package in Go programming language.

Wrong Way

When I want to show how to use Go methods in my blog posts, I usually put the example code in the testing as follows:

Method: hello.go

package hello

import (
      "fmt"
)

func Hello() {
      fmt.Println("hello world")
}

Usage: hello_test.go

package hello

import "testing"

func TestHello(t *testing.T) {
      // Example code here
}

One day @dchapes told me this is not a test, and @shurcooL showed me how to write examples in idiomatic Go way.

Idiomatic Go Way

@shurcooL told to use Examples in testing package [1]. The code in above Wrong Way section becomes:

Method: hello.go

package hello

import (
      "fmt"
)

func Hello() {
      fmt.Println("hello world")
}

Usage: hello_test.go

package hello

import "testing"

func ExampleHello(t *testing.T) {
      // Example code here
}

The standard Go testing package can runs and verifies example code if we follow the conventions in the testing code. This is a better and idiomatic way to show others how to use the methods in your package or code.


References:

[1]Examples - testing - The Go Programming Language