How to measure test coverage in Go

Overview

Go comes with a convenient tool for testing and coverage. Let’s create the following code for this shot. We have also added a test file below.

Example

We can execute the go test command from the folder containing the two files.

package main

import "testing"

func TestAdd(t *testing.T) {
	if got, want := World(1), "New World!"; got != want {
		t.Errorf("World method produced wrong result. expected: %s, got: %s", want, got)
	}
}
Executing "go test" command

When Go test is run, it executes the tests and prints either “PASS” or “FAIL”. Go allows us to get the coverage report with the built-in options to test command.

package main

import "testing"

func TestAdd(t *testing.T) {
	if got, want := World(1), "New World!"; got != want {
		t.Errorf("World method produced wrong result. expected: %s, got: %s", want, got)
	}
}
Executing "go test -coverprofile=coverage.out" command

We can also get a coverage report with line by line coverage details as follows:

package main

import "testing"

func TestAdd(t *testing.T) {
	if got, want := World(1), "New World!"; got != want {
		t.Errorf("World method produced wrong result. expected: %s, got: %s", want, got)
	}
}
Executing "go tool cover -html=coverage.out -o coverage.html "command

After executing Executing "go tool cover -html=coverage.out -o coverage.html command we get coverage.html file in our current directory. The following image shows the result of the HTML file.

"coverage.html" file output

As seen in the image above, the coverprofile gives us the details of the lines that have been covered by the tests versus those that have not been covered.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources