Go单元测试注意事项及测试单个方法和整个文件的命令

Go程序开发过程中免不了要对所写的单个业务方法进行单元测试,Go提供了 “testing” 包可以实现单元测试用例的编写,不过想要正确编写单元测试需要注意以下三点:

  • Go文件名必须以 "_test" 结尾
  • Go文件中的方法名必须以 “Test” 打头
  • 方法的形参必须为 (t *testing.T)

以下是我写的一个unit_test.go单元测试文件

package test

import (
    "testing"
    "fmt"
)

// 测试helloworld
func TestHelloWorld(t *testing.T) {
    fmt.Println("This is a HelloWorld unit test")
}

// 测试控制台打印
func TestPrint(t *testing.T) {
    fmt.Println("This is a Print unit test")
}

测试整个文件命令如下:

$ go test -v unit_test.go

结果如下:

=== RUN   TestHelloWorld
This is a HelloWorld unit test
--- PASS: TestHelloWorld (0.00s)
=== RUN   TestPrint
This is a Print unit test
--- PASS: TestPrint (0.00s)
PASS
ok      command-line-arguments  0.005s

测试单个方法命令如下:

$ go test -v unit_test.go -test.run TestHelloWorld

结果如下:

=== RUN   TestHelloWorld
This is a HelloWorld unit test
--- PASS: TestHelloWorld (0.00s)
PASS
ok      command-line-arguments  0.003s

转载于:https://www.cnblogs.com/qiangjiyi/p/9399894.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值