Go-Testing

Go-Testing

要点

Go的自动化测试框架比JUnit、PyUnit等更加轻量级。要点如下: 
- 测试代码以xxx_test.go方式命名 
- 测试代码中import “testing” 
- 测试函数形如 func Testxyz(t *Testing.T) {…} 
- 执行测试:go test

示例

比较要创建一个mymath package。

mymath.go

package mymath

func Add(x, y int) int {
    return x + y
}

func Minus(x, y int) int {
    return x - y
}

mymath_test.go

package mymath_test

import "mymath"
import "testing"

func TestAdd(t *testing.T) {
    ret := mymath.Add(2, 3)
    if ret != 5 {
        t.Error("Expected 5, got ", ret)
    }
}

func TestMinus(t *testing.T) {
    ret := mymath.Minus(2, 3)
    if ret != -1 {
        t.Error("Expected -1, got ", ret)
    }
}

目录文件结构

D:\examples>tree /F .
文件夹 PATH 列表
卷序列号为 5645-602F
D:\EXAMPLES
│  helloworld.exe
│  helloworld.go
│  math.txt
│  the_shape.go
│
└─the_go_path
    ├─pkg
    │  └─windows_amd64
    │          mymath.a
    │          shape.a
    │          shape2.a
    │
    └─src
        ├─mymath
        │      mymath.go
        │      mymath_test.go
        │
        ├─shape
        │      the_shape.go
        │
        └─shape2
                the_shape.go


D:\examples>

go test

这里略过go install。

mymath.go有错误的情况

D:\examples\the_go_path\src\mymath>go test
--- FAIL: TestMinus (0.00s)
        mymath_test.go:16: Expected -1, got  5
FAIL
exit status 1
FAIL    mymath  0.425s

D:\examples\the_go_path\src\mymath>

测试用例全部通过的情况

D:\examples\the_go_path\src\mymath>go test
PASS
ok      mymath  0.369s

D:\examples\the_go_path\src\mymath>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值