1

[Golang] Write Example Code in Testing

 2 years ago
source link: http://siongui.github.io/2017/03/26/go-show-example-code-in-testing/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK