社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
1:单元测试
要求:1:文件必须以*_test.go命名,这样在执行go test的时候才会执行到相应的代码
2:你必须import testing这个包
3:函数命名必须以Test*命名
4:命令:go test -v
示例:
package test
import (
"fmt"
"testing"
)
type user struct {
name string
age uint32
}
func (u *user) SetInfo(name string, age uint32) {
u.name = name
u.age = age
}
func (u *user) GetAge() uint32 {
return u.age
}
func TestInfo(t *testing.T) {
u := user{"Bob", 10}
u.SetInfo("Alice", 23)
age := u.GetAge()
fmt.Println(age)
}
执行go test -v 结果显示如下
2:基维测试
要求:1:文件必须以*_test.go命名,这样在执行go test的时候才会执行到相应的代码
2:你必须import testing这个包
3:函数命名必须以 Benchmark*命名
4:命令:go test -v -bench .(.代表执行所有的测试函数,不能少)
5:函数只接受一个唯一一个b *testing.B参数
示例:
package main
import (
// "fmt"
"testing"
)
const capacity = 1024
func array() [capacity]string {
var d [capacity]string
for i := 0; i < len(d); i++ {
d[i] = "hello"
}
return d
}
func slice() []int {
d := make([]string, capacity)
for i := 0; i < len(d); i++ {
d[i] = "world"
}
return d
}
func BenchmarkArray(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = array()
}
}
func BenchmarkSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = slice()
}
}
执行go test -v -bench .(第一列代表执行次数,第二列代表速度)
执行go test -v -bench . -benchmem(后两列结果代表执行内存分配的次数)
执行go test -v -bench . -benchmem -benchtime=”3s”(设置执行测试连续时间为3s)
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!