Go 测试单个方法

目录如下:

division.go代码如下:

package mytest

import (
    "errors"
)

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

divison_test.go代码如下:

package mytest

import "testing"

func Test_Division_1(t *testing.T) {
    if i, e := Division(6, 2); i != 3 || e != nil {
        t.Error("除法函数测试没通过") //如果不是预期的就报错
    } else {
        t.Log("第一个测试通过了") //可以记录一些需要的数据
    }
}

func Test_Division_2(t *testing.T) {
    if _, e := Division(6, 0); e == nil {
        t.Error("Division did not work as expected")
    } else {
        t.Log("one test is passed", e)
    }
}

1. 在目录下执行 go test  是测试目录所有以XXX_test.go 结尾的文件。

2.测试单个方法  下面2种写法。

  go test -test.v  -test.run="Test_Division_1" -test.count 5
      go test -v  -run="Test_Division_1" -count 5
3.查看帮助 go test -help  

原文地址:https://www.cnblogs.com/justdoyou/p/9972229.html