vscode配置go开发环境#
设置goroot
"go.goroot": "/usr/local/go-1.18.9"
,Ctrl + Shift + X
搜索安装Go插件Ctrl + Shift + P
执行命令Go: Install/Update Tools
,全选安装即可
自动创建单元测试#
Go函数右键点击Go: Generate Unit Tests For Function
示例
源码:
package utils
import "math"
// 判断浮点数是否是整数
// 依据就是指数是否大于等于小数位数
// 即1.2*10^2为整数,1.222*10^2为浮点数
// 改自《Go语言底层原理剖析》-郑建勋
func IsInt(f float64) bool {
bits := math.Float64bits(math.Abs(f))
bias := 1023 // 偏移量
exponent := int(bits>>52) - bias - 52 // 指数
coefficient := (bits & ((1 << 52) - 1)) | (1 << 52) // 系数 = 1 + 小数
intTest := (coefficient & (1<<uint32(-exponent) - 1))
// fmt.Printf("\nExponent: %d Coefficient: %d IntTest: %d\n", exponent, coefficient, intTest)
if exponent < -52 || (exponent < 0 && intTest != 0) {
return false
}
return true
}
单元测试:
package utils
import "testing"
func TestIsInt(t *testing.T) {
type args struct {
f float64
}
tests := []struct {
name string
args args
want bool
}{
{
name: "整数测试",
args: args{
f: 12344567,
},
want: true,
},
{
name: "小数测试",
args: args{
f: 1234456.7,
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsInt(tt.args.f); got != tt.want {
t.Errorf("IsInt() = %v, want %v", got, tt.want)
}
})
}
}
单元测试传参#
var _test = flag.Int64("test", 1069, "请输入计划ID")
func TestFoo(t *testing.T) {
// do something with variable _test
}
// 执行单元测试
go test -v -run TestFoo -test=123
执行单元测试#
- vscode操作
- 命令行执行
go test -v -run TestIsInt
问题#
beego单元测试配置文件加载问题#
如果待测试方法依赖到了配置文件,这时因为路径问题,可能无法加载
解决方法为在单元测试文件中手动加载配置文件
func init() {
appConfPath := "../../conf/app.conf"
err := web.LoadAppConfig("ini", appConfPath)
if err != nil {
logs.Error("LoadAppConfig: %v, config file: %v", err, appConfPath)
} else {
logs.Info("LoadAppConfig success")
}
}