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()
}
相关推荐
吧啦蹦吧2 天前
org.springframework.context.ApplicationListener
log4j
七夜zippoe4 天前
Agent 网关设计:统一入口、智能路由与负载均衡
运维·ai·log4j·负载均衡·agent·网关设计
汤姆宝库9 天前
推理时计算深拆:思维链、验证搜索与测试时Scaling
log4j
神一样的老师16 天前
WS63 嵌入式 SSD1306 OLED 驱动单元测试实战
单元测试·log4j
silvamux_18 天前
大模型 API 单元测试怎么 mock 不误伤
单元测试·log4j·php
system_error_x19 天前
自动化常规代码辅助系统
运维·自动化·log4j
看浪的路人19 天前
第10讲:大模型应用测试——从单元测试到 E2E 评测的完整体系
log4j
草莓熊Lotso21 天前
【C++ 基于微服务的即时通讯系统】基建三件套:gflags + gtest + spdlog 源码编译安装与实战入门
linux·网络·数据库·c++·微服务·log4j
j7~22 天前
【C++ 标准项目】发布订阅消息队列 (篇七):项目创建与基础工具模块搭建
开发语言·c++·log4j·uuid·protobuf·helper工具·消息定义类型和交换机类型定义
楚楚25123 天前
2026最新6款Cursor平替AI编程工具深度实测对比
log4j