Go代码测试覆盖率

  1. 目录结构

    ├── main.go
    └── main_test.go
    
  2. 代码

    // main.go
    package main
    import "fmt"
    func Divide(a, b float64) (float64, error) {
    	if b == 0 {
    		return 0, fmt.Errorf("division by zero is not allowed")
    	}
    
    	return a / b, nil
    }
    
    // main_test
    package main
    import "testing"
    func Test_Divide(t *testing.T) {
    	testCases := []struct {
    		a          float64
    		b          float64
    		expected   float64
    		shouldFail bool
    	}{
    		{10.0, 2.0, 5.0, false},
    		{15.0, 3.0, 5.0, false},
    	}
    
    	for _, tc := range testCases {
    		result, err := Divide(tc.a, tc.b)
    
    		if tc.shouldFail {
    			if err == nil {
    				t.Errorf("Expected an error for %f/%f but got none", tc.a, tc.b)
    			}
    		} else {
    			if err != nil {
    				t.Errorf("Unexpected error for %f/%f: %s", tc.a, tc.b, err)
    			}
    
    			if result != tc.expected {
    				t.Errorf("Expected %f/%f to be %f, but got %f", tc.a, tc.b, tc.expected, result)
    			}
    		}
    	}
    }
    
    
  3. 执行以下命令,生成文件c.out

    go test -coverprofile=c.out
    
  4. 执行以下命令,会自动打开浏览器

    go tool cover -html=c.out
    
  5. 会看到以下结果
    image