How to do it...

These steps cover writing and running your application:

  1. From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter9/coverageand navigate to this directory.
  2. 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    
  1. 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
}
  1. Run the gotests -all -w command.
  2. 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)
}
})
}
}
  1. Fill in the TODO section with the following:
        {"no condition", args{true}, true},
  1. 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
  1. Add the following item to the TODO section:
        {"condition", args{false}, false},
  1. 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
  1. Run the following commands:
$ go test -coverprofile=cover.out 
$ go tool cover -html=cover.out -o coverage.html
  1. Open the coverage.html file in a browser to see a graphical coverage report.
  2. The go.mod file may be updated and the go.sum file should now be present in the top-level recipe directory.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.93.44