Go语言 - Go单元测试(2)

Go单元测试(1)进行了Go语言简单的测试,下面记录一下Go更多的测试参数。

在hello目录下创建test子目录,最终的目录结构如下:

E:.
└─hello
    ├─sub
    └─test

将之前sub子目录的 add_test.go 移动到test子目录中(不迁移的话,无法使用go test filename进行测试,不知道为什么?)。

修改 add_test.go 的源码,main/sub包,并调整调用的方式sub.Add

package test

import (
	"testing"
	"main/sub"
)

/**
 * 测试add.go的Add方法
 */
func TestAdd(t *testing.T)  {
	sum := sub.Add(1, 2)
	if sum != 3 {
		t.Errorf("Add(1, 2) 测试失败,返回值为%v, 1 + 2 应该等于 3.", sum)
	}
}

func TestAddFail(t *testing.T) {
	sum := sub.Add(1, 2)
	if sum != 3 {
		t.Errorf("测试失败模拟 %v != 4", sum)
	}
}

运行整体测试:

# -v 查看测试信息
cd test
go test -v .

在hello目录中指定测试文件:

go test -v  .\test\add_test.go

指定测试用例,add_test.go 中有两个测试用例, 可以使用 --run 指定需要运行的测试用例:

go test -v -run TestAddFail .\test\add_test.go

==============================================================================
关注 公众号 “HiIT青年” 发送 “go” 获取go安装包。(如果没有收到回复,说明之前取消过关注。)

HiIT青年
关注公众号,阅读更多文章。

posted @ 2021-07-18 12:34  HiIT青年  阅读(44)  评论(0编辑  收藏  举报