Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to measure test coverage in Go

Anjana Shankar

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)
	}
}

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)
	}
}

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)
	}
}

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
communitycreator
RELATED COURSES

View all Courses

Keep Exploring