I need to calculate code coverage for golang project where source of tests will be integration tests written in Java language . This requires go build to be instrumented first and then run on server so that tests can run and we will get to know after tests have ended, how much is code coverage? I haven't found a single reference for this on internet all there is present is unit tests which can be run easily and used to calculate coverage
-
1`go test -covermode`?Java tests is no idea – Para Nov 14 '22 at 05:41
2 Answers
First of all generate the coverage profile by using the -coverprofile
flag and tell the command where to store the information.
% go test ./... -coverprofile cover.out
? some.project/somepkg [no test files]
ok some.project/somepkg/service 0.329s coverage: 53.3% of statements
Than use go tool cover
with the -func
flag and point it to the previously generated file. This will show you the code coverage for every single package withing your project and down at the bottom the total coverage.
% go tool cover -func cover.out
some.project/somepkg/service/.go:27: FuncA 100.0%
some.project/somepkg/service/service.go:33: FuncB 100.0%
some.project/somepkg/service/service.go:51: FuncC 0.0%
total: (statements) 53.3%
% go tool cover -func cover.out | fgrep total:
total: (statements) 53.3%
% go tool cover -func cover.out | fgrep total | awk '{print $3}'
100.0%
% go tool cover -func cover.out | fgrep total | awk '{print substr($3, 1, length($3)-1)}'
100.0

- 4,024
- 3
- 30
- 48
-
1problem with this approach is, instumented build needs to be up and running so that my java based tests can run on that . Here you are saying to run command go test ./... -coverprofile cover.out which will execute just unit tests and close the go build . – Shreenivash Dec 07 '22 at 07:20
Before go 1.20 you could not do it. Only coverage for unit tests was supported.
However with go 1.20 it is now possible
https://go.dev/testing/coverage/:
Beginning in Go 1.20, Go supports collection of coverage profiles from applications and from integration tests, larger and more complex tests for Go programs.
To collect coverage data for a program, build it with go build's -cover flag, then run the resulting binary with the environment variable GOCOVERDIR set to an output directory for coverage profiles. See the 'coverage for integration tests' landing page for more on how to get started. For details on the design and implementation, see the proposal.

- 1
- 2