Golang单元测试举例

1.第一个例子

cal.go

Go 复制代码
package main

func addUpper(n int) int {
	res := 0
	for i := 1; i <= n; i++ {
		res += i
	}
	return res
}

func getSub(n1 int, n2 int) int {
	return n1 - n2
}

cal_test.go

Go 复制代码
package main

//测试文件名必须是_test.go结尾
//测试函数必须Test开头
import (
	"fmt"
	"testing"
)

// 编写要给测试用例,去测试addUpper是否正确
func TestAddUpper(t *testing.T) {
	//调用
	res := addUpper(10)
	if res != 55 {
		//输出错误信息,退出程序
		t.Fatalf("AddUpper(10)执行错误,期望值=%v,实际值=%v\n", 55, res)
	}
	//如果正确,输出日志
	t.Logf("AddUpper(10) 执行正确...")
}

func TestHello(t *testing.T) {
	fmt.Println("TestHello被调用了")
}

// 编写要给测试用例,去测试addUpper是否正确
func TestGetSub2(t *testing.T) {
	//调用
	res := getSub(10, 3)
	if res != 7 {
		t.Fatalf("getSub(10,3)执行错误,期望值=%v,实际值=%v\n", 7, res)
	}
	//如果正确,输出日志
	t.Logf("getSub(10,3) 执行正确...")
}

说明:再GoLand中,要运行测试哪个函数可以自行选择

测试文件名必须以_test.go结尾;

测试方法的开头必须是Testxxx()

2.第二个例子,测试对象的序列化和反序列化

monster.go

Go 复制代码
package test2

import (
	"encoding/json"
	"fmt"
	"os"
)

type Monster struct {
	Name  string
	Age   int
	Skill string
}

// 序列化对象
func (this *Monster) Store() bool {
	//先序列化
	data, err := json.Marshal(this)
	if err != nil {
		fmt.Println("marshal err=", err)
		return false
	}
	//保存到文件
	filePath := "e:/monster.ser"
	err = os.WriteFile(filePath, data, 0666)
	if err != nil {
		fmt.Println("write file err=", err)
		return false
	}
	return true
}

// 反序列化对象
func (this *Monster) ReStore() bool {
	//1.从文件中读取序列化字符串
	filePath := "e:/monster.ser"
	data, err := os.ReadFile(filePath)
	if err != nil {
		fmt.Println("ReadFile err=", err)
		return false
	}

	//2.使用data []byte 反序列化
	err = json.Unmarshal(data, this)
	if err != nil {
		fmt.Println("Unmarshal err=", err)
		return false
	}
	return true
}

monster_test.go

Go 复制代码
package test2

import (
	"fmt"
	"testing"
)

func TestStrore(t *testing.T) {
	//先创建一个Monster
	monster := &Monster{
		Name:  "林动",
		Age:   20,
		Skill: "大荒芜经",
	}
	res := monster.Store()
	if !res {
		t.Fatalf("monster.Store()错误,希望为=%v 实际为=%v\n", true, res)
	}
	t.Logf("monster.Store() 测试成功")
}

func TestReStore(t *testing.T) {
	//先创建一个Monster实例,不需要指定字段的值
	var monster = &Monster{}
	res := monster.ReStore()
	if !res {
		t.Fatalf("monster.ReStore() 错误,希望=%v 实际为=%v\n", true, res)
	}
	//进一步判断
	fmt.Printf("%v %v %v\n", monster.Name, monster.Age, monster.Skill)
}
Go 复制代码
=== RUN   TestReStore
林动 20 大荒芜经
--- PASS: TestReStore (0.00s)
PASS
相关推荐
花酒锄作田9 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12310 天前
matlab画图工具
开发语言·matlab
dustcell.10 天前
haproxy七层代理
java·开发语言·前端
norlan_jame10 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone10 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549610 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月10 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_5312371710 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian10 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript