golang 单元测试框架(testing)

栏目: Go · 发布时间: 7年前

内容简介:要开始一个单元测试,需要准备一个 go 源码文件,在命名文件时需要让文件必须以_test结尾单元测试源码文件可以由多个测试用例组成,每个测试用例函数需要以Test为前缀,例如:![VR[)QZIRY

golang单元测试

要开始一个单元测试,需要准备一个 go 源码文件,在命名文件时需要让文件必须以_test结尾

单元测试源码文件可以由多个测试用例组成,每个测试用例函数需要以Test为前缀,例如:

func TestXXX( t *testing.T )
  • 测试用例文件不会参与正常源码编译,不会被包含到可执行文件中。
  • 测试用例文件使用 go test 指令来执行,没有也不需要 main() 作为函数入口。所有在以_test结尾的源码内以Test开头的函数会自动被执行。
  • 单元测试文件 (*_test.go) 里的测试入口必须以 Test 开始,参数为 *testing.T 的函数。一个单元测试文件可以有多个测试入口。
  • 使用 testing 包的 T 结构提供的 Log() 方法打印字符串。

代码目录结构如下

![VR[)QZIRY %9OL0QTIQ7%MD.png

##源文件
//uc.go
package uc

import "strings"

func UpperCase(str string) string {

return strings.ToUpper(str)}

测试文件

package uc
import "testing"
type ucTest struct {
    in, out string
}

var ucTests = []ucTest{
    ucTest{"abc", "ABC"},
    ucTest{"cvo-az", "CVO-AZ"},
    ucTest{"Antwerp", "ANTWERP"},
}

func TestUC(t *testing.T) {
    for _, ut := range ucTests {
        uc := UpperCase(ut.in)
        if uc != ut.out {
            t.Errorf("uppercase(%s) = %s,must be %s", ut.in, uc, ut.out)
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Code Reading

Code Reading

Diomidis Spinellis / Addison-Wesley Professional / 2003-06-06 / USD 64.99

This book is a unique and essential reference that focuses upon the reading and comprehension of existing software code. While code reading is an important task faced by the vast majority of students,......一起来看看 《Code Reading》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

SHA 加密
SHA 加密

SHA 加密工具