/**
 * @ClassName: add_test.go
 * @author: xiaosheng
 * createTime: 2023-03-24
 */

func TestAdd(t *testing.T) {
    if testing.Short() {
        t.Skip("short模式下跳过 耗时较长的测试用例")
    }
    re := add(1, 5)
    if re != 6 {
        t.Errorf("expect %d, actual %d, ", 6, re)
    } else {
        t.Logf("success expect:%d, actual %d", 6, re)
    }
}

/**
基于表格的单元测试
 */
func TestAdd(t *testing.T) {
    var dataset = []struct {
        a int
        b int
        c int
    }{
        {1, 1, 2},
        {2, 3, 5},
        {4, 5, 9},
        {-1, -2, -3},
        {-1, 2, 1},
    }
    for _, v := range dataset {
        re := add(v.a, v.b)
        if re != v.c {
            t.Errorf("expect %d, actual %d, ", v.c, re)
        } else {
            t.Logf("success expect:%d, actual %d", v.c, re)
        }
    }
}

/**
go test -bench=".*"
 */
func BenchmarkAdd(bb *testing.B) {
    var a, b, c int
    a = 123
    b = 345
    c = 468
    for i := 0; i < bb.N; i++ {
        if act := add(a, b); act != c {
            bb.Errorf("expect %d, actual %d, ", c, act)
        }
    }
}

const numbers = 10000

func BenchmarkStringSprintf(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        var str string
        for j := 0; j < numbers; j++ {
            str = fmt.Sprintf("%s-%d", str, j)
        }
    }
    b.StopTimer()
}

/**
推荐字符串拼接用下面的方式
 */
func BenchmarkStringAdd(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        var builder strings.Builder
        for j := 0; j < numbers; j++ {
            builder.WriteString(strconv.Itoa(j))
        }
        _ = builder.String()
    }
    b.StopTimer()
}
分类: 随笔

站点统计

  • 文章总数:309 篇
  • 分类总数:19 个
  • 标签总数:191 个
  • 运行天数:1009 天
  • 访问总数:129708 人次

浙公网安备33011302000604

辽ICP备20003309号