Tips for Go — BDD Testing, Mocking, and Coverage Analysis

TLDR — the code for getting the above coverage can be found here

Tip #1 — Behaviour Driven Development (BDD) with Ginkgo and Gomega

For more examples for testing in Go, see the official documentation here.

1. Install Ginkgo and Gomega to your project:

go get -u
go get

2. Change directory to the target package that you want to test

3. Run the following bootstrap command in the intended directory:

ginkgo bootstrap

4. Generate the test file to implement your tests:

ginkgo generate %FILENAME%

Tip #2 — Mocking calls and return values with GoMock

1. Install the required library with the following command:

GO111MODULE=on go get

2. Find the package and file that you want to mock and run the following command:

mockgen -source=pathTo/file.go -destination=pathTo/newMockFile.go

3. Import the generated mock file package in your test file, and use it to initialize the mock instance

Demonstrating how to import a generated mock file, and initializing it— source: example-test-go repo

Tip #3 — Use the Go CLI for more than just simple testing

HTML coverage analysis — in green are those covered in tests, while red lines are entirely absent

Staff Engineer, Hubble | Former Tech Lead, Rakuten Viki |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store