测试工具 :go test

go test 本身可以携带很多的参数,熟悉这些参数,可以让我们的测试过程更加方便。

1 运行整个项目的测试文件

$ go test
PASS
ok      _/home/wangbm/golang/math   0.003s

2 只运行某个测试文件

math_test.go
math.go 是一对,缺一不可,前后顺序可对调。

$ go test math_test.go math.go
ok      command-line-arguments  0.002s

3 加 -v 查看详细的结果

$ 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 只测试某个函数

-runTestAddTestAdd02
$ 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 参数

$ 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 参数

$ 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 参数

# 这里没有输出
$ go test -i
单元测试

准备两个 Go 文件::

E:\TEXT\test_go\test\math\math.go
package math

func Add(x, y int) int {
	return x + y
}
E:\TEXT\test_go\test\math\math_test.go
package math

import "testing"

func TestAdd(t *testing.T) {
	t.Log(Add(1, 2))
}

然后使用 go test 工具去执行:

PS E:\TEXT\test_go\test\math> go test .
ok      test/math       0.365s
PS E:\TEXT\test_go\test\math>

PS E:\TEXT\test_go\test\math> go test . -v
=== RUN   TestAdd
    math_test.go:6: 3
--- PASS: TestAdd (0.00s)
PASS
ok      test/math       0.359s
PS E:\TEXT\test_go\test\math>

从上面这个例子中,可以总结中几点 Go 语言测试框架要遵循的规则:

_test.gotesting.T
表组测试

Add(1, 2) 是一次单元测试的场景,而 Add(2, 4) ,Add(3, 6) 又是另外两种单元测试的场景。

对于多种输入场景的测试,我们可以同时放在 TestAdd 里进行测试,这种测试方法就是表组测试。

E:\TEXT\test_go\test\math\math_test.go
package math

import "testing"

func TestAdd(t *testing.T) {
	sum := Add(1, 2)
	if sum == 3 {
		t.Log("the result is ok")
	} else {
		t.Fatal("the result is wrong")
	}

	sum = Add(2, 4)
	if sum == 6 {
		t.Log("the result is ok")
	} else {
		t.Fatal("the result is wrong")
	}
}
PS E:\TEXT\test_go\test\math> go test . -v
=== RUN   TestAdd
    math_test.go:8: the result is ok
    math_test.go:15: the result is ok
--- PASS: TestAdd (0.00s)
PASS
ok      test/math       0.356s
PS E:\TEXT\test_go\test\math>

如果输入的场景实在太多(比如下面用的五组输入),用上面的方法,可能需要写很多重复的代码,这时候可以利用表格测试法

E:\TEXT\test_go\test\math\math_test.go
package math

import (
	"fmt"
	"testing"
)

type TestTable struct {
	xarg int
	yarg int
}

func TestAdd(t *testing.T) {
	tables := []TestTable{
		{1, 2},
		{2, 4},
		{4, 8},
		{5, 10},
		{6, 12},
	}

	for _, table := range tables {
		result := Add(table.xarg, table.yarg)
		if result == (table.xarg + table.yarg) {
			t.Log("" + fmt.Sprintf("the result is ok %d", result))
		} else {
			t.Fatal("the result is wrong")
		}
	}
}
PS E:\TEXT\test_go\test\math> go test . -v
=== RUN   TestAdd
    math_test.go:25: the result is ok 3
    math_test.go:25: the result is ok 6
    math_test.go:25: the result is ok 12
    math_test.go:25: the result is ok 15
    math_test.go:25: the result is ok 18
--- PASS: TestAdd (0.00s)
PASS
ok      test/math       0.351s
PS E:\TEXT\test_go\test\math>
理清 Go 中晦涩难懂的寻址问题

什么叫可寻址?

可直接使用 & 操作符取地址的对象,就是可寻址的(Addressable)。

E:\TEXT\test_go\test\math\math.go
package math

import "fmt"

func Unit() {
	name := "heihie"
	fmt.Println(&name)
}
E:\TEXT\test_go\test\math\math_test.go
PS E:\TEXT\test_go\test\math> go test . -v
=== RUN   TestUnit
0xc0000505a0
--- PASS: TestUnit (0.00s)
PASS
ok      test/math       0.313s
PS E:\TEXT\test_go\test\math>
name

但不能说 “iswbm” 这个字符串是可寻址的。

“iswbm” 是字符串,字符串都是不可变的,是不可寻址的,后面会介绍到。

在开始逐个介绍之前,先说一下结论:

&Profile{}name := Profile{}Profile{}

哪些是可以寻址的?

变量:&x

func main() {
    name := "iswbm"
    fmt.Println(&name)
    // output: 0xc000010200
}

指针:&*x

type Profile struct {
    Name string
}

func main() {
    fmt.Println(unsafe.Pointer(&Profile{Name: "iswbm"}))
    // output: 0xc000108040
}

数组元素索引: &a[0]

func main() {
    s := [...]int{1,2,3}
    fmt.Println(&s[0])
    // output: xc0000b4010
}

切片

func main() {
    fmt.Println([]int{1, 2, 3}[1:])
}

切片元素索引:&s[1]

func main() {
    s := make([]int , 2, 2)
    fmt.Println(&s[0])
    // output: xc0000b4010
}

组合字面量不可寻址字段属性可寻址

所有的组合字面量都是不可寻址的,就像下面这样子

type Profile struct {
    Name string
}

func new() Profile {
    return Profile{Name: "iswbm"}
}

func main() {
    fmt.Println(&new())
    // cannot take the address of new()
}
&
type Profile struct {
    Name string
}

func main() {
    fmt.Println(&Profile{Name: "iswbm"}) // ok
}

虽然组合字面量是不可寻址的,但却可以对组合字面量的字段属性进行寻址(直接访问)

type Profile struct {
    Name string
}

func new() Profile {
    return Profile{Name: "iswbm"}
}

func main() {
    fmt.Println(new().Name)
}

哪些是不可以寻址的?

常量

import "fmt"

const VERSION  = "1.0"

func main() {
    fmt.Println(&VERSION)
}

字符串

func getStr() string {
    return "iswbm"
}
func main() {
    fmt.Println(&getStr())
    // cannot take the address of getStr()
}

函数或方法

func getStr() string {
    return "iswbm"
}
func main() {
    fmt.Println(&getStr)
    // cannot take the address of getStr
}

基本类型字面量

字面量分:基本类型字面量复合型字面量

基本类型字面量,是一个值的文本表示,都是不应该也是不可以被寻址的。

func getInt() int {
    return 1024
}

func main() {
    fmt.Println(&getInt())
    // cannot take the address of getInt()
}

map 中的元素

字典比较特殊,可以从两个角度来反向推导,假设字典的元素是可寻址的,会出现 什么问题?

  1. 如果字典的元素不存在,则返回零值,而零值是不可变对象,如果能寻址问题就大了。
  2. 而如果字典的元素存在,考虑到 Go 中 map 实现中元素的地址是变化的,这意味着寻址的结果也是无意义的。

基于这两点,Map 中的元素不可寻址,符合常理。

func main() {
    p := map[string]string {
        "name": "iswbm",
    }

    fmt.Println(&p["name"])
    // cannot take the address of p["name"]
}

搞懂了这点,你应该能够理解下面这段代码为什么会报错啦~

E:\TEXT\test_go\test\math\math.go
package math

import "fmt"

type Person struct {
	Name  string
	Email string
}

func Unit() {
	m := map[int]Person{
		1: Person{"Andy", "1137291867@qq.com"},
		2: Person{"Tiny", "qishuai231@gmail.com"},
		3: Person{"Jack", "qs_edu2009@163.com"},
	}

	//编译错误:cannot assign to struct field m[1].Name in map
	// m[1].Name = "Scrapup"
	fmt.Println(m[1].Name)
}
E:\TEXT\test_go\test\math\math_test.go
package math

import (
	"fmt"
	"testing"
)

func TestUnit(t *testing.T) {
	Unit()
}

func TestCc(t *testing.T) {
	fmt.Println("hello")
}
PS E:\TEXT\test_go\test\math> go test -v -run="TestUnit"
=== RUN   TestUnit
Andy
--- PASS: TestUnit (0.00s)
PASS
ok      test/math       0.339s
PS E:\TEXT\test_go\test\math>

解决map修改值的方法

package math

import "fmt"

type Person struct {
	Name  string
	Email string
}

func Unit() {
	m := map[int]Person{
		1: Person{"Andy", "1137291867@qq.com"},
		2: Person{"Tiny", "qishuai231@gmail.com"},
		3: Person{"Jack", "qs_edu2009@163.com"},
	}

	// 创建一个新的Person
	newPerson := Person{Name: "Scrapup", Email: "1137291867@qq.com"}
	// 创建一个新的map
	newMap := make(map[int]Person)

	// 遍历原始map
	for k, v := range m {
		// 如果键值不等于1,则复制元素
		if k != 1 {
			newMap[k] = v
		} else {
			// 否则,添加新的Person
			newMap[k] = newPerson
		}
	}
	// 将新的map赋值给原始map
	m = newMap
	//打印结果
	for k, v := range m {
		fmt.Printf("key is %d, value is %v)\n", k, v)
	}
}

数组字面量进行切片操作

数组字面量是不可寻址的,当你对数组字面量进行切片操作,其实就是寻找内部元素的地址,下面这段代码是会报错的。

func main() {
    fmt.Println([3]int{1, 2, 3}[1:])
    // invalid operation [3]int literal[1:] (slice of unaddressable value)
}