GoFrame 單元測(cè)試-gtest

2022-04-12 11:00 更新

?gtest?模塊提供了簡(jiǎn)便化的、輕量級(jí)的、常用的單元測(cè)試方法。是基于標(biāo)準(zhǔn)庫(kù)?testing?的功能擴(kuò)展封裝,主要增加實(shí)現(xiàn)了以下特性:

  • 單元測(cè)試用例多測(cè)試項(xiàng)的隔離。
  • 增加常用的一系列測(cè)試斷言方法。
  • 斷言方法支持多種常見格式斷言。提高易用性。
  • 測(cè)試失敗時(shí)的錯(cuò)誤信息格式統(tǒng)一。

?gtest?設(shè)計(jì)為比較簡(jiǎn)便易用,可以滿足絕大部分的單元測(cè)試場(chǎng)景,如果涉及更復(fù)雜的測(cè)試場(chǎng)景,可以考慮第三方的?testify?、?goconvey?等測(cè)試框架。

使用方式:

import "github.com/gogf/gf/v2/test/gtest"

接口文檔:

https://pkg.go.dev/github.com/gogf/gf/v2/test/gtest

func C(t *testing.T, f func(t *T))
func Assert(value, expect interface{})
func AssertEQ(value, expect interface{})
func AssertGE(value, expect interface{})
func AssertGT(value, expect interface{})
func AssertIN(value, expect interface{})
func AssertLE(value, expect interface{})
func AssertLT(value, expect interface{})
func AssertNE(value, expect interface{})
func AssertNI(value, expect interface{})
func Error(message ...interface{})
func Fatal(message ...interface{})

簡(jiǎn)要說明:

  • 使用?C?方法創(chuàng)建一個(gè)?Case?,表示一個(gè)單元測(cè)試用例。一個(gè)單元測(cè)試方法可以包含多個(gè)?C?,每一個(gè)?C?包含的用例往往表示該方法的其中一種可能性測(cè)試。
  • 斷言方法?Assert?支持任意類型的變量比較。?AssertEQ?進(jìn)行斷言比較時(shí),會(huì)同時(shí)比較類型,即嚴(yán)格斷言。
  • 使用大小比較斷言方法如?AssertGE?時(shí),參數(shù)支持字符串及數(shù)字比較,其中字符串比較為大小寫敏感。
  • 包含斷言方法?AssertIN?及?AssertNI?支持?slice?類型參數(shù),暫不支持?map?類型參數(shù)。

用于單元測(cè)試的包名既可以使用包名?_test?,也可直接使用包名(即與測(cè)試包同名)。兩種使用方式都比較常見,且在Go官方標(biāo)準(zhǔn)庫(kù)中也均有涉及。但需要注意的是,當(dāng)需要測(cè)試包的私有方法/私有變量時(shí),必須使用包名命名形式。且在使用包名命名方式時(shí),注意僅用于單元測(cè)試的相關(guān)方法(非?Test*?測(cè)試方法)一般定義為私有,不要公開。

使用示例:

例如?gstr?模塊其中一個(gè)單元測(cè)試用例:

package gstr_test

import (
    "github.com/gogf/gf/v2/test/gtest"
    "github.com/gogf/gf/v2/text/gstr"
    "testing"
)

func Test_Trim(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
        t.Assert(gstr.Trim(" 123456\n "),      "123456")
        t.Assert(gstr.Trim("#123456#;", "#;"), "123456")
    })
}

也可以這樣使用:

package gstr_test

import (
    . "github.com/gogf/gf/v2/test/gtest"
    "github.com/gogf/gf/v2/text/gstr"
    "testing"
)

func Test_Trim(t *testing.T) {
    C(t, func() {
        Assert(gstr.Trim(" 123456\n "),      "123456")
        Assert(gstr.Trim("#123456#;", "#;"), "123456")
    })
}

一個(gè)單元測(cè)試用例可以包含多個(gè)?C?,一個(gè)?C?也可以執(zhí)行多個(gè)斷言。 斷言成功時(shí)直接?PASS?,但是如果斷言失敗,會(huì)輸出如下類似的錯(cuò)誤信息,并終止當(dāng)前單元測(cè)試用例的繼續(xù)執(zhí)行(不會(huì)終止后續(xù)的其他單元測(cè)試用例)。

=== RUN   Test_Trim
[ASSERT] EXPECT 123456#; == 123456
1. /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/v2/text/gstr/gstr_z_unit_trim_test.go:20
2. /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/v2/text/gstr/gstr_z_unit_trim_test.go:18
--- FAIL: Test_Trim (0.00s)
FAIL


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)