golang代码规范和单元测试

代码规范

方便团队内部统一风格,提高代码可读性,统一性

命名规范

  1. 包名
    1. 尽量和目录名一致
    2. 采用有意义,简短
    3. 不要和标准库冲突
    4. 包名应该尽量全部小写
  1. 文件名
    1. 如果多个单词可以采用蛇形命名法
  1. 变量名
    1. 蛇形 不使用
    2. 驼峰 go un userName
    3. 专有名词全大写或者全小写
  1. 结构名
    1. 驼峰 首字母大写
  1. 接口命名
    1. 和结构体差不多
    2. 接口已er结尾
    3. IR
  1. 常量命名
    1. 全部大写,多个单词采用蛇形APP_VERSION

注释规范:

go提供两种注释:

  1. //适合单行注释
  2. 大段注释
  3. 变量后面加注释
  4. 包注释
  5. 接口注释
  6. 函数注释
  7. 代码逻辑注释

import注释

  1. go自带的包
  2. 第三方的包
  3. 自己内部的包

单元测试

单元测试命令:go test

go test命令是一个按照一定约定和组织的测试代码驱动程序。在包目录中,所有以_test.go为后缀的源码文件都会被go test运行

我们写的__test.go源码文件不用担心内容过多,因为go build命令不会将这些测试文件打包到最后的可执行文件

test文件有4类,Test开头的 功能测试

Benchmark开头的 性能测试

example 模糊测试

复制代码
func TestAdd(t *testing.T) {

}

跳过耗时单元测试

复制代码
func TestAdd2 (t *testing.T) {
	if testing.Short() {
		t.Skip("short 模式下跳过")
	}
	re := add(a:1,b:2)
	if re != 3 {
	t.Errorf("expect %d,actual %d")
}
}

go test -short

运行一个短的

基于表格的测试用例

复制代码
func TestAdd(t *Testing.T) {
	var dataset = []struct{
	a int
	b int
	out int
	}{
	{a:1,b:2,out:3}
	{a:1,b:2,out:3}
	{a:1,b:2,out:3}
	{a:1,b:2,out:3}
	{a:1,b:2,out:3}
	}
	for _,value := range dataset {
	re := add(value.a,value.b)
	if re != value.out {
	t.Errorf("expect:%d,actual:%d",value.out,re)
	}
	}
}

性能测试

核心函数

复制代码
func BenchmarAdd(bb *testing.B) {
	var a,b,c int
	a = 123
	b = 456
	c = 789
	
	for i:= 0;i< bb.N;i++ {
	 if actual := add(a,b);actual != c{
	fmt.Printf("%d+%d,except:%d,actual:%d",a,b,c,actual)
	}
	}
}
实例

对三种字符串的拼接方式进行性能测试

复制代码
package light_edit

import (
	"fmt"
	"strconv"
	"strings"
	"testing"
)

const numbers = 10000

func BenchmarkStringBuilder(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()
}

func BenchmarkStringAdd(b *testing.B) {
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		var str string
		for j := 0; j < numbers; j++ {
			str = str + strconv.Itoa(j)
		}

	}
	b.StopTimer()

}

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()
}
相关推荐
周杰伦fans19 天前
记一次 Visual Studio 突然报错“未能加载 Microsoft.Internal.VisualStudio.Interop”的奇葩经历
microsoft·log4j·visual studio
laplaya19 天前
C++大型项目组件通信与依赖管理实践
c++·log4j·apache
福大大架构师每日一题20 天前
ollama v0.30.7 正式发布:Hermes 桌面端落地,接口、文档、底层依赖全方位优化
golang·log4j
四问四不知21 天前
Understand Anything的初步了解
log4j
wh_xia_jun22 天前
单元测试 + Mockito 开发指南
oracle·单元测试·log4j
kTR2hD1qb23 天前
Privaze源码级避坑指南技术文章大纲
log4j
阿正的梦工坊23 天前
【Rust】10-Cargo、测试与实用开发工作流
java·rust·log4j
捏塔25 天前
完美自动生成单元测试SKILL
单元测试·log4j
AI浩25 天前
指令微调与对齐技术:SFT、RLHF、DPO、RLAIF 与 RLVR(分层式精讲)
log4j
有浔则灵1 个月前
从零开始构建 AI Agent(一):理解 Eino 的 Component 抽象与流式对话
人工智能·log4j