Trusted answers to developer questions

How to measure test coverage in Go

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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.

RELATED TAGS

golang
Did you find this helpful?