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()
}
相关推荐
希望永不加班4 天前
SpringBoot 集成测试:@SpringBootTest 与 MockMvc
java·spring boot·后端·log4j·集成测试
Howrun7779 天前
C++ 项目测试全指南:从 0 基础到落地实操
开发语言·c++·log4j
admin and root10 天前
从资产收集FUZZ接口到SQL注入案例
网络·数据库·sql·安全·web安全·渗透测试·log4j
Joy T11 天前
【Web3】智能合约质量保障工程:从单元测试到 Gas 效能优化
单元测试·log4j·web3·智能合约·hardhat
sg_knight13 天前
使用 Claude Code 写单元测试的实战方法
单元测试·log4j·ai编程
sthnyph13 天前
SpringBoot Test详解
spring boot·后端·log4j
brucelee18613 天前
Spring Boot 测试最佳实践
spring boot·后端·log4j
X-TIE14 天前
一次日志引发的“血案”:从 Log4j 1.x 锁竞争到 Log4j 2.x 异步写入实战
log4j
zdl68618 天前
SpringBoot Test详解
spring boot·后端·log4j
lierenvip19 天前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j