go_test的使用

go_test

一、Test

1. 使用介绍

  1. 测试函数以Test开头,只能有一个t *testing.T参数
  2. 输出:通过*testing.T 参数的断言函数检查。
  3. 执行:运行go test时自动运行

2. 用例

package main

import "testing"

func Hello() string {
    return "Hello, world"
}

func TestHello(t *testing.T) {
    got := Hello()
    want := "Hello, world"

    //使用go_test的时候会忽略fmt.printf
    if got != want {
        t.Errorf("got '%q' want '%q'", got, want)
    }
}

func TestHello2(t *testing.T) {

    assertCorrectMessage := func(t *testing.T, got, want string) {
        t.Helper()
        if got != want {
            t.Errorf("got '%q' want '%q'", got, want)
        }
    }

    t.Run("saying hello to people", func(t *testing.T) {
        got := Hello("Chris")
        want := "Hello, Chris"
        assertCorrectMessage(t, got, want)
    })

    t.Run("empty string defaults to 'world'", func(t *testing.T) {
        got := Hello("")
        want := "Hello, World"
        assertCorrectMessage(t, got, want)
    })

}

3.常见函数

t.Errorf()//如果有错误,则打印出来

t.Run(string,func)//启动一个子测试,测试的内容为func函数,为这个子测试取名为string

t.Helper()//告诉测试套件这个方法是辅助函数,当测试失败时所报告的行号将在函数调用中而不是在辅助函数内部。

二、示例函数

2.1. 使用介绍

  1. 示例函数以Example 开头
  2. 输出:通过 // Output: 注释检查标准输出。
  3. 执行:只有当包含 // Output: 注释时,在 go test 执行时才会运行。否之只会编译,不去运行

2.2. 用例


func Add(x, y int) int {
    return x + y
}

func ExampleAdd() {
    sum := Add(1, 5)
    fmt.Println(sum)
    // Output: 6
}

三、基准测试

3.1.介绍

基准测试(Benchmarking)在Go语言中是一种用于测量代码性能的测试方法。它通常用于评估代码的运行时间和资源消耗,帮助开发者找到性能瓶颈并优化代码。基准测试的函数以 Benchmark 开头,放在 _test.go 文件中,与普通的测试函数和示例函数放在一起。下面是详细介绍如何编写和运行基准测试。

  1. 基准测试必须以Benchmark开头,必须接受一个b *testing.B类型的参数
  2. 基准测试的核心是一个循环,执行要测试的代码 b.N
  3. 注意:b.N是自动调整的值,用于确保基准测试运行足够长的时间以提供可靠的测量结果

3.2.使用实例

package iteration

import "testing"

func Repeat(character string) string {
    var repeated string
    for i := 0; i < 5; i++ {
        repeated += character
    }
    return repeated
}

func BenchmarkRepeat(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Repeat("a")
    }
}

3.3.常见函数

b.StopTimer()//停止计时器
b.StartTimer()//启动计时器
b.ResetTimer() // 重置计时器,忽略初始化时间

3.4 运行结果实例

运行以下命令:

go test -bench ^BenchmarkRepeat$ ./for/v3

示例输出:

goos: windows
goarch: amd64
pkg: github.com/xvxing/learn-go-with-tests/for/v3
cpu: 13th Gen Intel(R) Core(TM) i9-13980HX
BenchmarkRepeat-32    	19619479	        59.18 ns/op	      16 B/op	       4 allocs/op
PASS
ok  	github.com/xvxing/learn-go-with-tests/for/v3	1.244s
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值