These steps cover writing and running your application:
- From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter9/coverage, and navigate to this directory.
- Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter9/coverage
You should see a file called go.mod that contains the following:
module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter9/coverage
- Create a file called coverage.go with the following content:
package main
import "errors"
// Coverage is a simple function with some branching conditions
func Coverage(condition bool) error {
if condition {
return errors.New("condition was set")
}
return nil
}
- Run the gotests -all -w command.
- This will generate a file named coverage_test.go with the following content:
package main
import "testing"
func TestCoverage(t *testing.T) {
type args struct {
condition bool
}
tests := []struct {
name string
args args
wantErr bool
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := Coverage(tt.args.condition); (err != nil)
!= tt.wantErr {
t.Errorf("Coverage() error = %v, wantErr %v",
err, tt.wantErr)
}
})
}
}
- Fill in the TODO section with the following:
{"no condition", args{true}, true},
- Run the go test -cover command, and you will see the following output:
$ go test -cover
PASS
coverage: 66.7% of statements
ok github.com/PacktPublishing/Go-Programming-Cookbook-Second-
Edition/chapter9/coverage 0.007s
- Add the following item to the TODO section:
{"condition", args{false}, false},
- Run the go test -cover command, and you will see the following output:
$ go test -cover
PASS
coverage: 100.0% of statements
ok github.com/PacktPublishing/Go-Programming-Cookbook-Second-
Edition/chapter9/coverage 0.007s
- Run the following commands:
$ go test -coverprofile=cover.out
$ go tool cover -html=cover.out -o coverage.html
- Open the coverage.html file in a browser to see a graphical coverage report.
- The go.mod file may be updated and the go.sum file should now be present in the top-level recipe directory.