美文网首页
GO学习笔记(17) -测试

GO学习笔记(17) -测试

作者: 卡门001 | 来源:发表于2021-07-12 23:26 被阅读0次

测试工具 —go test

  • go test命令用于对Go语言编写的程序进行测试。

测试规范

  • 测试文件必须为"_test.go"为结尾, go test在执行时才会运行到相应的代码
  • 测试代码必须 import testing 这个包
  • 所有的测试用例函数必须是 Test 开头,测试函数 func TestXxxx(t *testing.T)中,除了Xxxx可以不一样外,别的格式都不能改,参数是 testing.T ,我们可以使用该类型来记录错误或者是测试状态
  • 函数中通过调用 testing.T 的 Error, Errorf, FailNow, Fatal, FatalIf 方法,说明测试不通过,调用 Log 方法用来记录测试的信息。

命令操作

  • 性能测试
go test -bench=.*
  • 单个方法测试
go test -v -test.run TestQueryYellowPagesMessageWithStaff
  • 一般测试
go test

测试方法—格驱动测试

package tests

import (
    "math"
    "testing"
)

//表格驱动设计
func TestTriangle(t *testing.T)  {
    tests := [] struct{a,b,c int}{
        {1,2,3},
        {3,4,5},
        {0,0,0},
        {4,5,6},
        {100,200,20000},
    }

    for _, tt := range tests{
        if actual := calcTriangle(tt.a,tt.b); actual != tt.c{
            t.Error(" calcTriangle(tt.%d,tt.%d); got %d ;expected %d",
            tt.a,tt.b,actual,tt.c)
        }
    }
}


func calcTriangle(a, b int) int {
    var c int
    c = int(math.Sqrt(float64(a*a + b*b)))
    return c
}

相关文章

网友评论

      本文标题:GO学习笔记(17) -测试

      本文链接:https://www.haomeiwen.com/subject/brymultx.html