I have a project like this:
app/
api/
foo.go
test_foo.go
src/
db/
bar.go
In foo.go
, a call is made to a function in bar.go
. However, when running the coverage report, it shows that 0 lines of bar.go are covered.
Is there a way to get coverage to include function call to other packages?
In my case, I do not want to make separate tests for db
and for api
, since all calls through db
will always go through api
, and it would be redundant to write two tests.
I'm running the coverage like this:
go clean -testcache
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
You need to include the coverpkg
flag so:
go test -coverpkg=./... coverprofile=coverage.out ./...
Would calculate the coverage on all of your packages.
https://golang.org/cmd/go/#hdr-Testing_flags
Short answer. To see correct coverages run:
go test ./... -coverprofile=coverage.out -coverpkg=./...
go tool cover -html=coverage.out
And then see percentages in dropdown inside browser.
Longer answer with explanation why other ways not worked. So, I also have a project with api
and store
(in this question it is called db
) packages, where store
is used in api
, and I have tests in api
.
go test -cover ./...
Says that api
is covered, store
- "[no test files]".
When I run it like
go test -cover -coverpkg=./... ./...
It decreases coverage in api
because now that number means how testcases in api
package cover all the packages, which is not very useful number.
But there is a way to know how given package is covered by tests in all the packages (eg, how store
is covered by tests from api
and other places).
First, you generate coverage profile:
go test ./... -coverprofile=coverage.out -coverpkg=./...
Above command will still give you wrong percents in output, but it will create coverage.out
file that will list all the lines in all packages covered by tests in all packages.
Then you could view this report in the browser with the command:
go tool cover -html=coverage.out
Then in the dropdown that allows you to select files to browse coverage for, you will get correct per file coverages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With