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

如何測試 Go 中未匯出的函數?

Mary-Kate Olsen
發布: 2024-10-26 05:47:02
原創
873 人瀏覽過

How Can You Test Unexported Functions in Go?

從非測試 Go 檔案呼叫測試函數

在 Go 中,不應從程式碼本身呼叫測試函數。相反,單元測試應該使用 go test 來執行。命令。

黑白盒測試

Go 支援兩種類型的單元測試:黑盒和白盒。

黑盒測試 測試從包外部導出的函數,模擬外部包如何與其互動。

白盒測試 測試包本身內部未匯出的函數。

範例

考慮一個名為 example 的套件,其中包含匯出的函數 Sum 和未匯出的實用函數 add。

<code class="go">// example.go
package example

func Sum(nums ...int) int {
    sum := 0
    for _, num := range nums {
        sum = add(sum, num)
    }
    return sum
}

func add(a, b int) int {
    return a + b
}</code>
登入後複製

黑盒測試(在example_test.go 中):

<code class="go">package example_test

import (
    "testing"

    "example"
)

func TestSum(t *testing.T) {
    tests := []struct {
        nums []int
        sum  int
    }{
        {nums: []int{1, 2, 3}, sum: 6},
        {nums: []int{2, 3, 4}, sum: 9},
    }

    for _, test := range tests {
        s := example.Sum(test.nums...)
        if s != test.sum {
            t.FailNow()
        }
    }
}</code>
登入後複製

白盒測試(在測試):

<code class="go">package example

import "testing"

func TestAdd(t *testing.T) {
    tests := []struct {
        a   int
        b   int
        sum int
    }{
        {a: 1, b: 2, sum: 3},
        {a: 3, b: 4, sum: 7},
    }

    for _, test := range tests {
        s := add(test.a, test.b)
        if s != test.sum {
            t.FailNow()
        }
    }
}</code>
登入後複製

總之,單元測試應該使用go test 指令執行,而不是直接從程式碼內部呼叫。黑盒和白盒測試為測試目的提供了對包實現的不同級別的存取。

以上是如何測試 Go 中未匯出的函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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