go test 单元函数测试

首先安装单元测试包,go get github.com/smartystreets/goconvey/convey

源程序如下,定义了加减乘除4个函数

package test222

import (
    "errors"
)

func Add(a, b int) int {
    return a + b 
}

func Subtract(a, b int) int {
    return a - b 
}

func Multiply(a, b int) int {
    return a * b 
}

func Division(a, b int) (int, error) {
    if b == 0 { 
        return 0, errors.New("被除数不能为 0") 
    }   
    return a / b, nil 
}

 测试程序如下

package test222

import (
    "testing"

    . "github.com/smartystreets/goconvey/convey"
)

func TestAdd(t *testing.T) {
    Convey("将两数相加", t, func() {
        So(Add(1, 2), ShouldEqual, 4)
    })  
}

func TestSubtract(t *testing.T) {
    Convey("将两数相减", t, func() {
        So(Subtract(1, 2), ShouldEqual, -1) 
    })  
}

func TestMultiply(t *testing.T) {
    Convey("将两数相乘", t, func() {
        So(Multiply(3, 2), ShouldEqual, 6)
    })  
}

func TestDivision(t *testing.T) {
    Convey("将两数相除", t, func() {

        Convey("除以非 0 数", func() {
            num, err := Division(10, 2)
            So(err, ShouldBeNil)
            So(num, ShouldEqual, 5)
        })  

        Convey("除以 0", func() {
            _, err := Division(10, 0)
            So(err, ShouldNotBeNil)
        })  
    })  
}

测试文件的格式有几点要求:

1  测试程序的package名必须和源程序相同

2  文件名必须是*_test.go的类型,*代表要测试的文件名

3  函数名必须以Test开头如:TestXxx或Test_xxx

4  测试函数TestXxx()的参数是*testing.T

5 测试内容都包含在Convey函数中

测试方法:

1  测试单个文件

    go test -v  func_test.go func.go

2  测试单个方法

    go test -v -test.run TestAdd

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值