Unit testing Golang using testify

Talking about basic and practice unit testing Golang using testify

Muhammad Isa
2 min readJul 15, 2021

Unit Test

Unit test is testing specific method using several test cases, that performed by the developer which create the method, to prove the method running as expected.

Get Started

Let’s say we have a method that generate OTP code that we can specify the length of the generated OTP code, and we want to test it, in this story I’ll using testify for assertion toolkit.

Here is OTP function code

Let’s Test it

In golang test file should be inside the same package of the function which will be tested, for better understand your OTP generator method is inside otp.go and the test file should be otp_test.go, here is the sample structure of file.

And here is otp_test.go file.

Detail for assertion from testify you can read the documentation in it’s github page.

Run go test recursively in root of project directory.

go test -v ./...

Result should be looks like this.

Run go test result

Run go test with coverage file and show the coverage in browser.

go test ./... -coverprofile cover.outgo tool cover -html=cover.out

And automatically open browser and show the detail coverage of the OTP code statements.

Golang test tool will highlight the covered statement with green, and uncovered statement with red highlight.

Thanks you.

--

--