Home  >  Article  >  Backend Development  >  How to compare test coverage value of Golang test cases with specific threshold

How to compare test coverage value of Golang test cases with specific threshold

WBOY
WBOYforward
2024-02-08 23:39:20389browse

如何将 Golang 测试用例的测试覆盖率值与特定阈值进行比较

phpIn this article, I will introduce to you how to compare the test coverage value of Golang test cases with a specific threshold. In software development, test coverage is an important metric, which measures how well test cases cover the code. By comparing the test coverage value with a specific threshold, we can judge the quality of the test cases and discover insufficient test coverage in time, thereby improving the quality and stability of the code. In this article, we will explain how to use Golang’s testing tools and code coverage tools to calculate test coverage and compare it to a specific threshold. Whether you are a beginner or an experienced developer, this article will provide you with practical tips and methods to help you better manage and evaluate test coverage. Let’s explore together!

Question content

I want to get the test coverage and compare it to a user defined threshold. I tried the code below in the makefile I referenced from this link. It's written in a .yml file, but I'm trying to write it in a 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

It doesn't print anything on echo ${totaltestcoverage} and gives the answer "ok" even though my totaltestcoverage is 40.

Can anyone help me find a better way to get test coverage and compare to user defined thresholds?

Thanks in advance.

Solution

You can try this

.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

The above is the detailed content of How to compare test coverage value of Golang test cases with specific threshold. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete