dongyonglie5132 2016-05-21 13:38
浏览 271
已采纳

获取golang测试的分支机构覆盖率

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?

  • 写回答

1条回答 默认 最新

  • dtt83024 2018-11-20 15:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?