原文: https://studygolang.com/articles/17010

--------------------------

 

要开始一个单元测试,需要准备一个 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)
        }
    }
}

相关文章:

  • 2021-11-25
  • 2021-12-30
  • 2021-12-04
  • 2022-12-23
  • 2021-05-11
  • 2021-06-30
  • 2021-10-24
  • 2021-04-13
猜你喜欢
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
  • 2022-02-07
  • 2021-08-18
  • 2022-03-10
  • 2021-12-20
相关资源
相似解决方案