首页

    go test -coverpkg to increase coverage

    标签:go

    go test -cover默认只统计被测试过的package(即有*_test.go文件)的coverage.下面目录结构

    .
    └── pkg
        ├── http2
        │   ├── client.go
        │   ├── http2_test.go
        │   └── server.go
        ├── network
        │   ├── common.go
        │   └── dns.go
    

    network包里的代码测试覆盖不到,即使测试确实跑到了network包,这时的codecov,看看network包里的代码,都是简单的调用,Google已经测试过了,难道要写个network_test.go,把Google的测试代码复制进去?
    当然可以将network包的文件复制到http2包

     .
    ├── http2
    │   ├── client.go
    │   ├── dns.go
    │   ├── dns_test.go
    │   ├── http2_test.go
    │   ├── network.go
    │   └── server.go
    

    这样原来network包的代码都覆盖到了,这时的codecov

    然而,很多时候为了代码复用,确实需要network包,只需加上-coverpkg,指明测试需要覆盖的包

    -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.
    
    go test -count=1 -v -coverprofile=coverage.txt -coverpkg=./http2,./network -covermode=atomic -race ./...
    

    执行后的codedev