# 6.1 Go 命令:go test 工具详解
接下来几篇文章,我将介绍 下 Golang 中有关测试相关的一些文章。
在学习如何编写测试代码之前,需要先了解一下Go 提供的测试工具 :go test
go test 本身可以携带很多的参数,熟悉这些参数,可以让我们的测试过程更加方便。
下面就根据场景来解释一下常用的几个参数:
(由于下一节才会讲到如何编写测试代码,所以请好结合下一篇文章进行学习)
1、运行整个项目的测试文件
```shell
$ go test
PASS
ok _/home/wangbm/golang/math 0.003s
```
2、只运行某个测试文件( math_test.go, math.go 是一对,缺一不可,前后顺序可对调)
```shell
$ go test math_test.go math.go
ok command-line-arguments 0.002s
```
3、加 `-v` 查看详细的结果
```shell
$ go test math_test.go math.go
=== RUN TestAdd
TestAdd: main_test.go:22: the result is ok
TestAdd: main_test.go:22: the result is ok
TestAdd: main_test.go:22: the result is ok
TestAdd: main_test.go:22: the result is ok
TestAdd: main_test.go:22: the result is ok
--- PASS: TestAdd (0.00s)
PASS
ok command-line-arguments 0.003s
```
4、只测试某个函数,-run 支持正则,如下例子中 TestAdd,如果还有一个测试函数为 TestAdd02,那么它也会被运行。
```shell
$ go test -v -run="TestAdd"
=== RUN TestAdd
TestAdd: math_test.go:22: the result is ok
TestAdd: math_test.go:22: the result is ok
TestAdd: math_test.go:22: the result is ok
TestAdd: math_test.go:22: the result is ok
TestAdd: math_test.go:22: the result is ok
--- PASS: TestAdd (0.00s)
PASS
ok _/home/wangbm/golang/math 0.003s
```
5、生成 test 的二进制文件:加 `-c` 参数
```shell
$ go test -v -run="TestAdd" -c
$
$ ls -l
total 3208
-rw-r--r-- 1 root root 95 May 25 20:56 math.go
-rwxr-xr-x 1 root root 3272760 May 25 21:00 math.test
-rw-r--r-- 1 root root 525 May 25 20:56 math_test.go
```
6、执行这个 test 测试文件:加 `-o` 参数
```shell
$ go test -v -o math.test
=== RUN TestAdd
TestAdd: math_test.go:22: the result is ok
TestAdd: math_test.go:22: the result is ok
TestAdd: math_test.go:22: the result is ok
TestAdd: math_test.go:22: the result is ok
TestAdd: math_test.go:22: the result is ok
--- PASS: TestAdd (0.00s)
=== RUN TestAum
TestAum: math_test.go:30: 6
--- PASS: TestAum (0.00s)
PASS
ok _/home/wangbm/golang/math 0.002s
```
7、只测试安装/重新安装 依赖包,而不运行代码:加 `-i` 参数
```shell
# 这里没有输出
$ go test -i
```
- 第一章:基础知识
- 1.1 一文搞定开发环境的搭建
- 1.2 五种变量创建的方法
- 1.3 数据类型:整型与浮点型
- 1.4 数据类型:byte、rune与字符串
- 1.5 数据类型:数组与切片
- 1.6 数据类型:字典与布尔类型
- 1.7 数据类型:指针
- 1.8 流程控制:if-else
- 1.9 流程控制:switch-case
- 1.10 流程控制:for 循环
- 1.11 流程控制:goto 无条件跳转
- 1.12 流程控制:defer 延迟语句
- 1.13 流程控制:理解 select 用法
- 1.14 异常机制:panic 和 recover
- 1.15 语法规则:理解语句块与作用域
- 第二章:面向对象
- 2.1 面向对象:结构体与继承
- 2.2 面向对象:接口与多态
- 2.3 面向对象:结构体里的 Tag 用法
- 2.4 学习接口:详解类型断言
- 2.5 学习接口:Go 语言中的空接口
- 2.6 学习接口:接口的三个"潜规则"
- 2.7 学习反射:反射三定律
- 2.8 学习反射:全面学习反射的函数
- 2.9 详细图解:静态类型与动态类型
- 2.10 关键字:make 和 new 的区别?
- 第三章:项目管理
- 3.1 依赖管理:包导入很重要的 8 个知识点
- 3.2 依赖管理:超详细解读 Go Modules 应用
- 3.3 开源发布:如何开源自己写的包给别人用?
- 3.4 代码规范:Go语言中编码规范
- 第四章:并发编程
- 4.1 学习 Go 函数:理解 Go 里的函数
- 4.2 学习 Go 协程:goroutine
- 4.3 学习 Go 协程:详解信道/通道
- 4.4 学习 Go 协程:WaitGroup
- 4.5 学习 Go 协程:互斥锁和读写锁
- 4.7 学习 Go 协程: 信道死锁经典错误案例
- 4.7 学习 Go 协程:如何实现一个协程池?
- 4.8 理解 Go 语言中的 Context
- 4.9 学习一些常见的并发模型
- 第五章:学标准库
- 5.1 fmt.Printf 方法详解
- 5.2 os/exec 执行命令的五种姿势
- 第六章:开发技能
- 6.1 Go 命令:go test 工具详解
- 6.2 单元测试:如何进行单元测试?
- 6.3 调试技巧:使用 GDB 调试 Go 程序
- 6.4 Go 命令: Go 命令指南
- 第七章:暂未分类
- 7.1 20 个学习 Go 语言的精品网站
