首頁  >  文章  >  後端開發  >  你可以在 Go 中從測試檔案外部呼叫測試函數嗎?

你可以在 Go 中從測試檔案外部呼叫測試函數嗎?

Patricia Arquette
Patricia Arquette原創
2024-10-26 06:32:02973瀏覽

Can You Call a Test Function from Outside a Test File in Go?

你可以從測試檔案外部呼叫測試函數嗎?

在 Go 中,單元測試通常使用 go test 運行,它識別並執行標記為的測試函數測試.T 參數。然而,問題出現了:可以從非測試檔案呼叫測試函數來啟動測試執行嗎?

答案:框架限制

不幸的是,答案是否定的。 Go 的測試框架旨在強制測試和非測試程式碼之間的分離。測試函數只能從測試文件中調用,並且被測試的單元必須從適當的套件中導入。

Go 中的測試模式

Go 支援兩種主要測試模式:

  • 黑盒測試:測試從包外部導出的函數,模擬其他包如何與它們互動。
  • 白盒測試: 從包內測試未導出的函數,提供對內部實作細節的存取。

將其付諸實踐

考慮一個名為 example 的範例包,其中包含 add 實用函數和導出的 Sum利用內部 add 函數的函數。

example.go:包含匯出和未匯出函數的軟體包

<code class="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>
example_internal_test.go 中的白盒測試
<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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn