go 单元测试

testing包提供对 Go 包的自动化测试的支

通过 `go test` 命令,能够自动执行如下形式的任何函数:

func TestXxx(te *testing.T) Test是固定的, *testing.T也是固定的参数类型

calc.go中 里面是目标函数, 没有任何要求

package test

// 加法计算函数
func CalcAdd(a, b int) int {
    return a + b
}

// 求余计算函数
func CalcRemainder(source, number int) int {
    return source % number
}

math_test.go里面是测试函数, 文件名中_test.go是固定的, 里面的函数名必须是Test开头 

package test
import (
    "testing"
)

// 单元测试- 求和
func TestAdd(t *testing.T) {
    sum := CalcAdd(3, 5)
    if sum != 8{
        t.Fatalf("CalcAdd is error")
    }
    t.Log("CalcAdd is ok")
}

// 单元测试- 求余数
func TestRemainder(t *testing.T) {
    remainder := CalcRemainder(99, 10)
    if remainder != 9{
        t.Fatalf("CalcRemainder is error")
    }
    t.Log("CalcRemainder is ok")
}

D:\golang\workspace\project\src\day8\example5\test>go test             // cd到测试文件所有目标, 直接运行 go test
PASS
ok      day8/example5/test      0.032s

--------------------------------------------------------------------------------

D:\golang\workspace\project\src\day8\example5\test>go test -v             // 有额外信息
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
    math_test.go:12: CalcAdd is ok

=== RUN   TestRemainder
--- PASS: TestRemainder (0.00s)
    math_test.go:21: CalcRemainder is ok

PASS
ok      day8/example5/test      0.035s

例: 测试 写入文件 与 读取文件的操作函数是否正确

fileOperator.go:

type Student struct{
    Name string
    Age int
    Score int	
}

// 将Student写入文件
func (stu *Student) SaveToFile(path string) error {
    data, ok := json.Marshal(stu)    // 将stu打包为json
    if ok != nil {
        return errors.New("打包失败")
    }
    err := ioutil.WriteFile(path, data, 0755)  // 如果写入正确, 则err为nil
    return err
}

// 从文件读Student数据到stu中(和上面函数相反的操作)
func (stu *Student) GetFromFile(path string) error{
	
    data, ok := ioutil.ReadFile(path)
    if ok != nil {
        return errors.New("读取文件失败")
    }

    err := json.Unmarshal(data, stu)    // 解析json
    return err
}

file_test.go:

func TestSaveToFile(t *testing.T){
    // 生成一个Student
    stu := &Student{
        Name : "张三",
        Age : 20,
        Score : 88,
    }
    // 执行写入函数
    err := stu.SaveToFile("c:/a.bat")
    if err != nil {
        t.Fatalf("写入失败")	// 这个自带return功能, 执行了它的话, 就结束了此测试函数
    }
    t.Log("写入成功")
}


func TestFileOperator(t *testing.T){
    stu1 := &Student{
        Name : "张三",
        Age : 20,
        Score : 88,
    }
    err1 := stu1.SaveToFile("c:/a.bat")
    if err1 != nil {
        t.Fatalf("写入失败")
    }

    // 再测试将其读出来, 放入stu2中
    var stu2 = &Student{}
    err2 := stu2.GetFromFile("c:/a.bat")
    if err2 != nil {
        t.Fatalf("读取失败")
    }

    // 可以判断写入的stu与读出来的stu是否是相同的(假设Name相同就认为相同)
    if stu1.Name == stu2.Name {		
        t.Log("读写正确")
    } else {
        t.Log("读写不正确")
    }
}

猜你喜欢

转载自blog.csdn.net/lljxk2008/article/details/87876975