Home > Article > Backend Development > How to cover code in Golang unit tests?
How to cover code in Golang unit tests? Method: Use the built-in cover tool (go test -cover). Utilize third-party libraries, such as testify's assert function. Practical example: Use the cover tool and testify assertion function to measure the code coverage of the Factorial function and generate an HTML report to display detailed information.
#How to cover code in Golang unit tests?
Introduction
Code coverage is a measure of the share of target code covered by a test suite. In unit testing, high code coverage indicates that most of the business logic has been tested, improving the reliability of the test.
Method
1. Use code coverage tool
Go language provides cover
tool to measure code coverage. To use it, in addition to the normal go test
command, you also need to add the -cover
flag:
go test -cover
2. Utilize third-party libraries
There are also many third-party libraries that can provide more detailed code coverage reports. For example, you can use the assert
function in testify
:
import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { assert.Equal(t, 1, something()) // 覆盖了 something() 函数的 return 语句 }
Practical case
The following is a simple Go language Function and related unit tests:
// main.go package main func Factorial(n int) int { if n == 0 { return 1 } return n * Factorial(n-1) } func main() { println(Factorial(5)) // 输出:120 }
// factorial_test.go package main import "testing" func TestFactorial(t *testing.T) { // 记录 Factorial 函数的覆盖率 t.Run("Cover", func(t *testing.T) { cases := []int{0, 1, 5, 10} for _, n := range cases { Factorial(n) } }) }
Run the tests:
go test -cover -coverprofile=cover.out
Then, use go tool cover -html=cover.out
to generate an HTML report that shows Coverage details.
The above is the detailed content of How to cover code in Golang unit tests?. For more information, please follow other related articles on the PHP Chinese website!