Go – Define Test Coverage in Golang – With Picture and Coverprofile – With YouTube Video

After ChatGPT showed me how to write tests in Golang (seriously!), I learned that there is a built-in feature, that actually shows the test coverage like this:

The greatest test coverage ever!

The green lines show you where the code has run and was tested and the red lines show where the code was still not covered by the tests. The magical way to get this is calling following line in the command line:

go test -coverprofile=cover.out & go tool cover -html=cover.out

Yes. This beauty works. I even made a YouTube video about it here, so I will not explain a lot to give you some insentives to watch it and become one of my subscribers. The code is below the video 🙂

Tests in Golang - Get test coverage with picture

main_test.go

package main

import (
	"testing"
)

var testSimpleFoo = []struct {
	name     string
	n        int
	expected int
	hasError bool
}{
	{"valid-test-0", 12, 60, false},
	{"valid-test-5", 4, -5, false},
	{"valid-test-5-and-10", 5, 10, false},
	{"valid-test-1", 0, 0, true},
	{"valid-test-2", 0, 0, true},
}

func TestSimpleFooFunction(t *testing.T) {
	for _, tt := range testSimpleFoo {
		result, err := SimpleFoo(tt.n)

		if err == nil && tt.hasError {
			t.Error("error was expected, but not received")
		}

		if err != nil && !tt.hasError {
			t.Error("error was not expected, but received", err.Error())
		}

		if result != tt.expected {
			t.Errorf("%v -> expected %v, result is %v", tt.name, tt.expected, result)
		}
	}
}

func TestSimpleFoo(t *testing.T) {
	result, _ := SimpleFoo(11)
	if result != 55 {
		t.Errorf("%v expected, but %v received", 55, result)
	}
}

func TestSimpleFooF(t *testing.T) {
	result, _ := SimpleFoo(11)
	if result != 57 {
		t.Errorf("%v expected, but %v received", 57, result)
	}
}

main.go

package main

import (
	"errors"
	"fmt"
)

func main() {
	fmt.Println(SimpleFoo(4))
}

func SimpleFoo(n int) (int, error) {

	result := 0
	if n == 0 {
		return result, errors.New("n cannot be 0 in SimpleFoo()")
	}

	if n > 5 {
		return n * 5, nil
	} else if n < 5 {
		return n - 5, nil
	} else {
		return n * 2, nil
	}
}

func SimpleBar(n int) (int, error) {

	result := 0

	if n == 20 {
		return result, errors.New("n cannot be 20 in SimpleBar")
	}

	if n > 10 {
		result = n * n
	} else if n < 5 {
		result = n - 10
	} else {
		result = n
	}
	return result, nil
}

Calling the tests is with one of the three options:

go test  – simply runs the tests

go test -v – one step further, gives information about the tests that are run;

go test -coverprofile true  – actually calculates the test coverage;

Enjoy!