Can someone suggest a way to me if we can get branch coverage for my golang tests? Let's say I have a golang code which looks like below:
package main
import (
"fmt"
)
func HelloWorld(name string, printv int) string {
if name == "tuk" || printv == 1 {
fmt.Println("Hello tuk")
return "Hello tuk"
} else {
fmt.Println("Who are you?")
return "Who are you?"
}
}
The corresponding test file looks like below:
package main
import "testing"
func TestHelloWorld(t *testing.T) {
r := HelloWorld("tuk", 0)
if r != "Hello tuk" {
t.Error("Test Failed")
}
}
If I execute the below test command, it is just giving me the statement coverage:
go test -coverprofile=cover.out .
ok test 0.007s coverage: 60.0% of statements
Is there a way I can get the branch coverage as well?
As of Go 1.11 (November 2018), the generated machine code for the coverage only covers each block of statements. It should be possible to take that code and adjust it to cover every branch of an expression.
It looks as if the gobco project has done exactly this, although only for single files and not for whole packages (again, as of November 2018).
I filed an issue to see whether branch coverage is considered to be worthwhile by the Go team. The decision is to keep the current code as simple as it is now, and that decision had already been documented in the code itself.
In the end I forked the gobco project and added all the features I need.