golang 测试模块使用

go 测试模块学习

go 测试的模块 testing

简单的功能测试,侧重于功能正确

被测试代码 位于项目 go/src/项目包/test
package goCode

func Add(a, b int) int {
  return a + b
}
测试代码 位于项目 go/src/项目包/test
package goCode_test

import (
  "testing"
  goCode "tsLearn/goCode"
)

func TestAdd(t *testing.T) {
  var a, b, c = 1, 2, 3
  real := goCode.Add(a, b)
  if real != c {
    t.Errorf("error Add")
  }
}
使用普通功能测试
cd 项目目录 
go test  即可
输出
PASS
ok      tsLearn/test    0.002s

侧重于性能测试,测试代码运行速度

被测试 性能 代码,侧重于性能测试
// 不提前分配 ,动态分配函数性能
func MakeSliceWithoutAlloc() []int {
  var newSlice []int
  for i := 0; i < 100000; i++ {
    newSlice = append(newSlice, i)
  }
  return newSlice
}

// 提前分配确定数量的 函数

func MakeSliceWithPreAlloc() []int {
  var newSlice []int
  newSlice = make([]int, 0, 100000)
  for i := 0; i < 100000; i++ {
    newSlice = append(newSlice, i)
  }
  return newSlice
}
测试性能 代码
func BenchmarkMakeSliceWithoutAlloc(b *testing.B) {
  for i := 0; i < b.N; i++ {
    goCode.MakeSliceWithoutAlloc()
  }
}

func BenchmarkMakeSliceWithPreAlloc(b *testing.B) {
  for i := 0; i < b.N; i++ {
    goCode.MakeSliceWithPreAlloc()
  }
}
使用测试方式
go test -bench=.

goos: linux
goarch: amd64
pkg: tsLearn/test
BenchmarkMakeSliceWithoutAlloc-8            1400            734023 ns/op
BenchmarkMakeSliceWithPreAlloc-8            7796            133683 ns/op
PASS
ok      tsLearn/test    2.182s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuemake999

请我喝茶呗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值