Home >Backend Development >Golang >How to analyze the test coverage report of golang function?
Generate the coverage configuration file through the go test -cover command, use the gocov tool to install and generate an HTML report to view detailed coverage information. Specific steps include: Install the gocov tool. To run unit tests, add the -cover flag: go test -cover. Generate a coverage report: gocov convert -html coverage.out > coverage.html.
How to analyze the test coverage report of Golang function
The test coverage report provides information about which parts of the code have been tested insights. This helps identify areas of code that are not covered and guides further testing efforts.
Use go test -cover
Go language has built-in go test -cover
command to generate test coverage Report. This command outputs a coverage configuration file that contains coverage information for each package and function.
Installation gocov
Tools
gocov
is a tool for visual coverage reporting. It can be installed from GitHub or via the following command:
go install github.com/wadey/gocov/gocov
Generate HTML Report
To generate interactive HTML reports, use the gocov
tool :
gocov convert -html coverage.out > coverage.html
The generated coverage.html
file can be opened in a web browser to view detailed coverage information.
Practical case
Suppose we have a function named add
that is used to add two integers:
package main func add(a, b int) int { return a + b } func TestAdd(t *testing.T) { tests := []struct { a, b int want int }{ {1, 2, 3}, {3, 4, 7}, } for _, test := range tests { if got := add(test.a, test.b); got != test.want { t.Errorf("add(%d, %d): got %d, want %d", test.a, test.b, got, test.want) } } }
Run coverage test
Use the go test -cover
command to run the unit test:
go test -cover
Generate coverage report
Generate and visualize the coverage report:
gocov convert -html coverage.out > coverage.html
Open the coverage.html
file and you can see the coverage percentage of the add
function. If coverage is less than 100%, it indicates that some code paths have not been covered by tests.
The above is the detailed content of How to analyze the test coverage report of golang function?. For more information, please follow other related articles on the PHP Chinese website!