go基础详解2-go run & test

一 go run

编译运行一个main 包(package),常用的运行方式如下:

go run .
go run hello

go run 后面接路径,该路径(不含子路径)下所有的go源文件都属于main包。

==go run filename1 filename1 ==

go run 后面接go源文件,这些源文件必须要属于main包(package),并且要列出该程序所需的所有的源文件

二、go test

go 有一个轻量级(lightweight)的单元测试(unit testing)框架,可以很方便的测试相关函数。在使用此测试框架的时候需要注意以下 几点:

1、一般情况下,测试文件与被测试文件在同一个目录下,也可以不在同一个目录下;

2、当在同一个目录下的时候,如果被测试文件所在的包是fmt,那么测试文件所在的包一定要是fmt_test,否则会报错;

S C:\Users\love1\Documents\technology\go\gopathMode\hello\yyzc> go test -v .\greetings_test.go

#command-line-arguments

greetings_test.go:5:8: found packages greet (greetings.go) and greet1 (greetings_test.go) in C:\Users\love1\Documents\technology\go\gopathMode\hello\yyzc

FAIL command-line-arguments setup failed

FAIL

3、测试文件需要以_test.go为结尾;

4、测试文件中一般会包含类似TestXXX命名的函数,go测试框架会依次运行这些函数,这些函数示例如下;

go 复制代码
func TestXXX (t *testing.T){
}

否则会报如下错误

:\Users\love1\Documents\technology\go\gopathMode\hello\yyzc\greetings_test.go:8:1: wrong signature for TestHello, must be: func TestHello(t *testing.T)

FAIL command-line-arguments setup failed

FAIL

PS C:\Users\love1\Documents\technology\go\gopathMode\hello\yyzc>

5、执行方式

go test . 执行当前目录下的所有test文件
go test directory 执行yyzc目录下的所有test文件
go test filename 只执行指定的test文件

相关推荐
ServBay6 小时前
打通 AI 编程本地运维边界,利用 MCP 协议简化环境与服务管理
后端·ai编程·mcp
程序员cxuan6 小时前
DeepSeek 杀入多模态,识图功能正式上线!
人工智能·后端·程序员
IT_陈寒9 小时前
SpringBoot这个自动配置坑我跳了三次
前端·人工智能·后端
用户3952409988010 小时前
排坑日记:ASP.NET Core 中 "Required field is not provided" 验证错误全记录
后端
用户83562907805110 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
Oneslide11 小时前
sudo免密权限配置不生效
后端
站大爷IP11 小时前
为什么Python不用var或let声明变量?
后端
赴星半途11 小时前
NestJS实战-创建AuthService
后端
北冥有鱼11 小时前
mqtt 测试
前端·后端