Test Coverage in Go

Aman Agarwal
2 min readMay 22, 2021

--

What is Unit testing ?

In computer programming, unit testing is a software testing method by which individual units of source code sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures are tested to determine whether they are fit for use.
And we all normally write a unit test for each section of code!

BUT Do we know how much code section is covered by our unit test, At some point yes but not always exactly. So that how the test coverage concept pops in.

What is Test Coverage ?

The section of code or amount of total code or method covered by our Unit test excluding declaration and initialization part. In Other Words, we can say Test coverage is a term that describes how much of a package’s code is exercised by running the package’s tests. If executing the test suite causes 80% of the package’s source statements to be run, we say that the test coverage is 80%.

How to Use and Work with it .

We simply write go test ./...to run all the test cases.
and so simple with help of go tool we can find out coverage percentage as well as can see the code that is covered, excluded and most important uncovered through HTML presentation of the source code decorated with coverage information.
we can also generate coverage profile using the Coverprofile tool

go test ./... -coverprofile = <filename>.out

go test ./... -coverprofile=test.out
ok calc 0.001s coverage: 100.0% of statements
ok calc/format 0.001s coverage: 100.0% of statements

We can also see the coverage score seperately for each function

go tool cover -func=<filename>.out

go tool cover -func test.out
calc/calc.go:4: Add 100.0%
calc/calc.go:9: Subtract 100.0%
calc/calc.go:14: Multiply 100.0%
calc/format/format.go:8: Print 100.0%

And for HTML presentation of coverage score and are in more detailed format

go tool cover -html=<filename>.out

go tool cover -html=test.out

When this command is run, a browser window pops up, showing the covered (green), uncovered (red), and not tracked(grey) source. Here’s a screen dump:

*Note

you will need to create a cover profile first to see its function and HTML scorecard of test coverage and use the same file name to access the binary cover profile file and use it for further examination.

--

--

Aman Agarwal

Engineer | Explorer | Blockchain | Golang | JavaScript developer