9

My project-structure
stuff/stuff.go -> package: stuff
test/stuff/stuff_test.go -> package: test
Although stuff_test executes code from stuff.go it shows
coverage: 0.0% of statements

I used go test -cover
If I move my *_test.go to the stuff-folder of the program it is working fine.
Or perhaps my approach of the project-structure is not well designed/go-conform?

3 Answers 3

5

Conventional Go program structure keeps the tests with the package. Like this:

project
|-stuff
|--stuff.go
|--stuff_test.go

At the top of your testing files you still declare package stuff, and it is required that your test methods take the form TestMethodX if you want go test to automatically run them.

See Go docs for details: https://golang.org/pkg/testing/

4

Cross-package test coverage is not directly supported, but several people have built wrappers to merge individual coverage profiles.

See Issue #6909 for the long history on this. And see gotestcover for an example tool to do the merging. There's also gocovmerge. I built my own version, so I haven't tried any of these, but I'm sure they all work like mine, and mine works fine.

My sense is that this is just an issue that no one has written a really compelling changelist for, and hasn't been that important to the core maintainers, so it hasn't been addressed. It does raise little corner cases that might break existing tests, so the quick hacks that work for most of us haven't been accepted as-is. But I haven't seen any discussion suggesting the core maintainers actively object to this feature.

2
  • Can you publish a link for your tool, Rob?
    – Rick-777
    Dec 31, 2015 at 10:38
  • @Rick-777 Mine is an internal tool that's integrated with our build system (with hardcoded paths and logic). I've considered making it generic and publishing it; it wouldn't be that much work. But there are already other good tools in this space, so there really isn't much need for yet another one.
    – Rob Napier
    Dec 31, 2015 at 14:18
3

You can use the -coverpkg option to select the packages for which to record coverage information.

From the output of go help testflag:

-coverpkg pattern1,pattern2,pattern3
Apply coverage analysis in each test to packages matching the patterns. The default is for each test to analyze only the package being tested. See 'go help packages' for a description of package patterns. Sets -cover.

For example:

go test ./test/... -coverprofile=cover.out -coverpkg ./...

Then view the report with:

go tool cover -html=cover.out
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.