Go Test

This article is about go unit test, in this article I will show some key and basic use for go.

Basic

  1. The test file must named as XXXX_test.go2.
  2. The test function must named with TestXXXX, then it can be call when you try to run it.

Test Type

There are two type of unit test.

  1. Basic unit test, it will be like format TestXX(t *testing.T){}
  2. Benchmark test, it will be lke the format TestXXX(t *testing.B){}

Run unit test

go test -v -gcflags=all=-l -count=1 /.go

  1. -v will show all the code coverage
  2. -gcflags=all=-l which won’t optimizte the code, if not add this flag, some cases may fail
  3. -count=1 which means do nont enable cache, if enable this, it can improve the performance

Run unit test in a container

For go unit test, it may fail when you try to run unit test on a machine such as my mac, it may fail and show error permission denied, so we can mount our code into a go docker and then run our unit test code in docker, this is a very useful method to run unit test. Here is the command:

 docker run -it -v /Users/wguan/work/code/study:/go --privileged docker.io/golang
 bash

Unit test

In order to write a good unit test, there are many things useful libraries which can help us.

Testify

For this package, the most use of this package is assert, we can use this package to assert many conditions.

Gomock

This package can only mock interface, and if you want to mock a function or method, it can not work very well. And for this package it also requires to generate mock code, it can’t mock directly.

gomonkey

Gomonkey is the most useful package for go test, it can mock all of the type function, methods, interface and variable. But some platforms may not support, so you have to run those unit tests in a docker.

gostub

Gostub is used to mock variable.

convey

convey is very useful and friendly unit test package, it can help us to print and shows case clearly.

Test console

There are some cases we print our result to the console, so we need to catch the output and compare the result, here is the example code.

function code:

package test

import "fmt"

func MyPrint() {
	fmt.Print("Hello World!")
}

Test code:

package test

import (
	"io/ioutil"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestMyPrint(t *testing.T) {
	rescueStdout := os.Stdout
	r, w, _ := os.Pipe()
	os.Stdout = w
	MyPrint()
	w.Close()
	out, _ := ioutil.ReadAll(r)
	os.Stdout = rescueStdout
	assert.Equal(t, string(out), "Hello World!")
}

Fuzzy Test

Fuzzy test just define some example cases, then it will generate other cases.

Built with Hugo
Theme Stack designed by Jimmy