go 單元測試

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

go 單元測試

  • go 單元測試
    • 概述
    • 執行個體
    • 參考文獻

概述

go 提供了自動化的測試的包 testing

假設我們有一個檔案youfile.go,那麼建立測試檔案的名字為 yourfile_test.go,這個檔案中有測試函數,形式如下:

func TestXxx(*testing.T)

其中 TestXxxXxx 的第一個字母 X 必須是大寫字母。

將你的源檔案 yourfile.goyourfile_test.go 放在同一個目錄下。
使用 go test 命令運行

執行個體

這裡使用 https://github.com/golang/example/tree/master/stringutil 的檔案測試
stringutil 目錄下有兩個檔案:reverse.goreverse_test.go

reverse.go

package stringutil// Reverse returns its argument string reversed rune-wise left to right.func Reverse(s string) string {    r := []rune(s)    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {        r[i], r[j] = r[j], r[i]    }    return string(r)}

reverse_test.go

package stringutilimport "testing"func TestReverse(t *testing.T) {    for _, c := range []struct {        in, want string    } {        {"Hello, world", "dlrow ,olleH"},        {"Hello, 世界", "界世 ,olleH"},        {"", ""},    } {        got := Reverse(c.in)        if got != c.want {            t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want)        }    }}

運行結果

[stringnutil]# go testPASSok    stringutil  0.002s

參考文獻

pkg/testing

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.