首页 > 文章列表 > 比较Golang测试用例的测试覆盖率值与特定阈值的方法

比较Golang测试用例的测试覆盖率值与特定阈值的方法

207 2024-02-09
问题内容

我想获取测试覆盖率并与用户定义的阈值进行比较。我在 makefile 中尝试了下面的代码,我引用了这个链接。它是写在 .yml 文件中的,但我试图将它写在 makefile 中。

.PHONY: lint    
testcoverage=$(go tool cover -func coverage.out | grep total | grep -Eo '[0-9]+.[0-9]+')
echo ${testcoverage}
if (${testcoverage} -lt 50 ); then 
  echo "Please add more unit tests or adjust threshold to a lower value."; 
  echo "Failed"
  exit 1
else 
  echo "OK"; 
fi

它不会在 echo ${totaltestcoverage} 上打印任何内容,并给出答案“ok”,即使我的 totaltestcoverage 是 40。

任何人都可以帮助我找到更好的方法来获得测试覆盖率并与用户定义的阈值进行比较吗?

提前致谢。


正确答案


你可以试试这个

.PHONY: lint

testcoverage := $(shell go tool cover -func=coverage.out | grep total | grep -Eo '[0-9]+.[0-9]+')
threshold = 50

test:
    @go test -coverprofile=coverage.out -covermode=count  ./...

check-coverage:
    @echo "Test coverage: $(testcoverage)"
    @echo "Test Threshold: $(threshold)"
    @echo "-----------------------"

    @if [ "$(shell echo "$(testcoverage) < $(threshold)" | bc -l)" -eq 1 ]; then 
        echo "Please add more unit tests or adjust the threshold to a lower value."; 
        echo "Failed"; 
        exit 1; 
    else 
        echo "OK"; 
    fi