產生覆蓋率報告#

# 執行測試並產生覆蓋率資料
go test -cover ./...

# 輸出覆蓋率資料到檔案
go test -coverprofile=coverage.out ./...

# 查看覆蓋率統計
go tool cover -func=coverage.out

# 產生 HTML 報告
go tool cover -html=coverage.out -o coverage.html

輸出範例#

ok      mypackage   0.123s  coverage: 78.5% of statements

--- coverage.out ---
mypackage/calculator.go:10:    Add         100.0%
mypackage/calculator.go:15:    Subtract    100.0%
mypackage/calculator.go:20:    Multiply    80.0%
mypackage/calculator.go:30:    Divide      50.0%
total:                         (statements) 78.5%

覆蓋模式#

# set: 是否被執行(預設)
go test -covermode=set -coverprofile=coverage.out

# count: 執行次數
go test -covermode=count -coverprofile=coverage.out

# atomic: 原子計數(用於併發測試)
go test -covermode=atomic -coverprofile=coverage.out
整合 CI/CD 的覆蓋率檢查
#!/bin/bash

# 產生覆蓋率報告
go test -coverprofile=coverage.out ./...

# 計算總覆蓋率
COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//')

# 檢查是否達標
THRESHOLD=80
if (( $(echo "$COVERAGE < $THRESHOLD" | bc -l) )); then
    echo "覆蓋率 ${COVERAGE}% 低於門檻 ${THRESHOLD}%"
    exit 1
fi

echo "覆蓋率檢查通過: ${COVERAGE}%"