美文网首页
golang test的几种使用类型

golang test的几种使用类型

作者: 哆啦在这A梦在哪 | 来源:发表于2022-05-23 16:16 被阅读0次

https://pkg.go.dev/testing?GOOS=darwin

1.T 基本测试

(测试调用当个方法)

// Test 开头,参数是 *testing.T ,调用 hello 方法
func TestHello(t *testing.T){
      hello()
}

2.B 标准测试

(循环n次调用的方法,相当于执行了基本测试n次,需要代码中写入)

// Benchmark 开头,参数是 *testing.B) ,调用 hello 方法
func BenchmarkRandInt(b *testing.B) {
    for i := 0; i < b.N; i++ {
        hello()
    }
}

3. E Examples

可以将输出和自己定义的结果进行比较

func ExampleHello() {
    fmt.Println("hello")
    // Output: hello
}

func ExampleSalutations() {
    fmt.Println("hello, and")
    fmt.Println("goodbye")
    // Output:
    // hello, and
    // goodbye
}
// 还可以不根据顺序进行比较判断,使用 Unordered
// 详细资料根据文档地址看

4. F 模糊测试 (随机传入参数)

// 使用 f.Add 加入需要执行的参数
//  f.Fuzz 中执行的方法中,参数会随机获取一个进行执行
func FuzzHex(f *testing.F) {
  for _, seed := range [][]byte{{}, {0}, {9}, {0xa}, {0xf}, {1, 2, 3, 4}} {
    f.Add(seed)
  }
  f.Fuzz(func(t *testing.T, in []byte) {
    enc := hex.EncodeToString(in)
    out, err := hex.DecodeString(enc)
    if err != nil {
      t.Fatalf("%v: decode: %v", in, err)
    }
    if !bytes.Equal(in, out) {
      t.Fatalf("%v: not equal after round trip: %v", in, out)
    }
  })
}

5.跳过某些错误使用 Skip 方法,

如果输入无效,*T 的 Skip 方法可用于模糊目标,但不应将其视为失败输入

func FuzzJSONMarshalling(f *testing.F) { 
    f.Fuzz(func(t *testing.T, b []byte) { 
        var v interface{} 
        if err := json.Unmarshal(b, &v); err != nil { 
            t.Skip()  // 如果在正常逻辑中应该反馈停止执行并反馈这个错误
        } 
        if _, err := json.Marshal(v); err != nil { 
            t.Error("Marshal: %v", err) 
        } 
    }) 
}

6.子测试和子基准

T 和 B 的 Run 方法允许定义子测试和子基准,而不必为每个定义单独的函数。这支持使用表驱动的基准测试和创建分层测试。它还提供了一种共享通用设置和拆卸代码的方法:

func TestFoo(t *testing.T) { 
    // <设置代码> 
    t.Run("A=1", func(t *testing.T) { ... }) 
    t.Run("A=2", func(t *testing.T) { ... }) 
    t.Run("B=1", func(t *testing.T) { ... }) 
    // <拆解代码> 
}

总结

1.上述记录了基本的一些方法;
2.还有很多其他很不错的方法请参考 go test 地址文档
比如 执行的几种方法

go test -run '' # 运行所有测试。
go test -run Foo # 运行匹配“Foo”的顶级测试,例如“TestFooBar”。
go test -run Foo/A= # 对于匹配“Foo”的顶级测试,运行匹配“A=”的子测试。
go test -run /A=1 # 对于所有顶级测试,运行匹配“A=1”的子测试。
go test -fuzz FuzzFoo # 模糊匹配“FuzzFoo”的目标

还可以有子测试也可用于控制并行性。只有在其所有子测试完成后,父测试才会完成。
以及 TestMain 的使用
TestMain 是一个低级原语,对于普通测试功能就足够了的临时测试需求,不应该是必需的。

相关文章

网友评论

      本文标题:golang test的几种使用类型

      本文链接:https://www.haomeiwen.com/subject/ylbrprtx.html