首頁 > 後端開發 > Golang > 主體

如何在與編譯的 Go 二進位檔案互動的功能測試中實現全面的覆蓋率設定檔而沒有盲點?

Susan Sarandon
發布: 2024-10-25 07:14:29
原創
533 人瀏覽過

How to achieve comprehensive coverage profiles without blind spots for functional tests interacting with a compiled Go binary?

顯示無盲點的功能測試覆蓋率

問題:

解決方案:

為了編寫沒有盲點的覆蓋率配置文件,建議從測試中排除main.go 文件。這可以使用建立標籤來完成,方法是將行 // build !test 新增到 main.go 檔案的頂部。這將指示 Go 編譯器在測試建置期間忽略該檔案。

以下是包含此方法的範例程式碼的修改版本:

<code class="go">// dofunc.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

var seed int64 = time.Now().UTC().UnixNano()

func doFunc() int {
    rand.Seed(seed)
    var code int
    for {
        i := rand.Int()
        fmt.Println(i)
        if i%3 == 0 {
            code = 0
            break
        }
        if i%2 == 0 {
            fmt.Println("status 1")
            code = 1
            break
        }
        time.Sleep(time.Second)
    }
    return code
}

// main.go
//+build !test
package main

import "os"

func main() {
    os.Exit(doFunc())
}

// dofunc_test.go
package main

import (
    "testing"
    "flag"
    "os"
)

var exitCode int

func TestMain(m *testing.M) {
    flag.Parse()
    code := m.Run()
    os.Exit(code)
}

func TestDoFuncErrorCodeZero(t *testing.T) {
    seed = 2

    if code := doFunc(); code != 0 {
        t.Fail()
    }
}

func TestDoFuncErrorCodeOne(t *testing.T) {
    seed = 3

    if code := doFunc(); code != 1 {
        t.Fail()
    }
}</code>
登入後複製

用法:

    使用標籤來覆寫二進位檔案:go test -c -coverpkg=。 -o myProgram -tags test
  1. 運行覆蓋率二進位檔案:./myProgram -test.coverprofile=/tmp/profile
  2. 產生覆蓋率HTML 報告:go tool cover -html /tmp/ profile -o /tmp/profile.html
透過從測試中排除main.go,exit() 函數不再是覆蓋率分析的一部分,並且覆蓋率設定檔將準確反映功能測試。

以上是如何在與編譯的 Go 二進位檔案互動的功能測試中實現全面的覆蓋率設定檔而沒有盲點?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!