Write unit test in Golang

Tram Ho

Standard package for Go unit testing: package testing

Package testing has in standard library since 2009. Convention of writing unit test in Go lang is: In file foo.go, will have file foo_test.go in same directory/folder. In file foo.go has method BlaBla(), and in foo_test.go has method TestBlaBla() accordingly.

I have file div.go has content

For unit testing, has file div_test.go has content

In this example, I used only Go standard library (supported by package testing).

Run unit testing with verbose information

Command for unit test running

Result

*testing.Parallel() create parallel flows for unit testing in concurrency.

Third-party library support Go lang unit testing

With supporting from package github.com/strectchr/testify , *assert.Nil() for assertion Nil value. *assert.Equal() for assertion of equalitation.

assert.Equal receive 3 parameters likes this, one and first parameter is *testing , 2 next parameters are variable and value of variable:

assert.Nil() receive 2 parameters likes this

Third-party libraries support Go lang unit testing

In source code, you don’t see declaring mockery in go.mod , it is tool installed to host machine.

Comand set Go to path

Install Mockery by command

Share the news now

Source : Viblo