您的位置 首页 golang

Golang笔记-单元测试test初探


为什么需要单元测试

其实在很长一段时间,包括现在,我都很不喜欢写单元测试。因为维护单元测试的成本很高。只有接口做了一点变更,那么单元测试就必须做相同的变更,否则会导致测试不通过。

那么反过来,只要每次在提交代码都去运行一次单元测试。这样可以很快的检查到你对代码更改是否影响了正常的业务逻辑,当然很大一部分是可能是别人写的那部分代码。因为你不确定本次的修改是否会影响到别人的那部分。所以单元测试还是很有必要的。

单元测试最基本的应用

go语言中单元测试是开箱即用的,官方提供了test包。不用像PHP中需要单独配置unit

go test 最基本使用

go test 命令是golang单元测试的最基本使用

go test -v

go test -v是我们比较常用的一个测试命令,用于执行测试,并打印额外的输出。

新建一个项目用于示例

test│  main.go│  main_test.go

可以看到我在main.go的同级目录创建了一个main_test.gogo语言中,单元测试的代码必须跟需要测试的代码在同一个包里面。且命名必须遵循上面的那种结构规范,即:文件名_test.go

我在main.go中创建两个函数来分别得到字符串相加的结果。

func JoinStrUseSprint(a,b string) string {    return  fmt.Sprintf("%s%s",a,b)}func JoinStrUseNor(a,b string) string {    return  a+b}

main_test.go中的测试代码

import "testing"func TestJoinStrUseNor(t *testing.T) {    c := JoinStrUseNor("aaa","bbb")    t.Log(c)}func TestJoinStrUseSprint(t *testing.T) {    c := JoinStrUseSprint("aaa","bbb")    t.Log(c)}

测试代码中使用了 testing包。而且每个测试函数必须是以Test开头,有且只有一个参数t *testing.T.t.Log()函数为输出一段Log日志 这样一个简单的单元测试就完成了。

这个时候我们运行go test,结果如下。

test>go testPASSok      test    0.360s

可以看到测试通过了。但是发现并没有我们期望的日志输出。如果我们要得到输出的结果,我们需要一个额外的参数,具体命令如下:

test>go test -v=== RUN   TestJoinStrUseNor--- PASS: TestJoinStrUseNor (0.00s)    main_test.go:7: aaabbb=== RUN   TestJoinStrUseSprint--- PASS: TestJoinStrUseSprint (0.00s)    main_test.go:12: aaabbbPASSok      test    0.480s

这个时候就可以看到很详细的测试流程与输出的测试的log

go test -cover

很多时间我们需要看单元测试的覆盖率,这个时候我们就需要go test -cover了。

我们同样使用上面的代码。

test>go test -coverPASScoverage: 100.0% of statementsok      test    0.440s

可以看到单元代码覆盖率是100%。这个是我们在main文件里面在增加一个函数。

func JoinStrUseSprint(a,b string) string {    return  fmt.Sprintf("%s%s",a,b)}func JoinStrUseNor(a,b string) string {    return  a+b}func Run()  {    fmt.Println("I'm run,and I'm happy!")}

然后再执行cover,得到了覆盖率为66.7

test>go test -coverPASScoverage: 66.7% of statementsok      test    0.398s

当然-v -cover是可以同事使用的。

test>go test -cover -v=== RUN   TestJoinStrUseNor--- PASS: TestJoinStrUseNor (0.00s)    main_test.go:7: aaabbb=== RUN   TestJoinStrUseSprint--- PASS: TestJoinStrUseSprint (0.00s)    main_test.go:12: aaabbbPASScoverage: 66.7% of statementsok      test    0.429s

很多时候我们需要将单元测试覆盖率写到一个文件中,这时候我们再-cover中增加一些额外的参数

>go test -coverprofile test.cover>go tool cover -html=test.cover -o coverage.html
  • 第一个命令:-coverprofile filename将覆盖率的profile写入指定文件中。
  • 第二个命令:go tool cover -html=test.cover -o coverage.html将覆盖率的文件写入可视化的html文件中

打开converage.html
如下图:
cover_01.png

其实这里可以借用一个很好的第三方包。

go get github.com/smartystreets/goconvey

安装完成,直接再项目目录下执行

test>goconvey2020/05/16 21:46:43 goconvey.go:61: Initial configuration: [host: 127.0.0.1] [port: 8080] [poll: 250ms] [cover: true]2020/05/16 21:46:43 tester.go:19: Now configured to test 10 packages concurrently.2020/05/16 21:46:43 goconvey.go:178: Serving HTTP at: http://127.0.0.1:80802020/05/16 21:46:43 integration.go:122: File system state modified, publishing current folders... 0 31792700492020/05/16 21:46:43 goconvey.go:118: Received request from watcher to execute tests...2020/05/16 21:46:43 goconvey.go:105: Launching browser on 127.0.0.1:80802020/05/16 21:46:43 goconvey.go:111: exec: "start": executable file not found in %PATH%2020/05/16 21:46:43 goconvey.go:113:2020/05/16 21:46:44 executor.go:69: Executor status: 'executing'2020/05/16 21:46:44 coordinator.go:46: Executing concurrent tests: test2020/05/16 21:46:45 parser.go:24: [passed]: test

按照提示打开http://127.0.0.1:8080/就会得到一个很炫酷的覆盖率界面
cover_02.png

Golang单元测试的基础今天就暂时到这里面,下面几个testing包的常用断言方法.

// 输出测试日志t.Logf()t.Logf()// 标记错误,但仍然执行后面的语句t.Fail()// 获取是否当前用例是执行错误的t.Failed()// 错误输出,等于 t.Logf 再执行 t.Fail()t.Errorf("%s", "run ErrorF")// 标记函数错误,并中断后面的执行t.FailNow()// 致命错误输出,等同于调用了 t.Logf 然后调用 t.FailNow()t.Fatalf("%s", "run Fatelf")

下一篇我们会写到 golang中的一些基准测试,以及一些测试的工具。

更多学习内容,同步更新到公众号,期待与您一起交流
白色底可爱幼稚微信公众号底部二维码.png


文章来源:智云一二三科技

文章标题:Golang笔记-单元测试test初探

文章地址:https://www.zhihuclub.com/257.shtml

关于作者: 智云科技

热门文章

评论已关闭

32条评论

  1. Therefore, before using this product, tell your doctor or pharmacist of all the products you use 180pills 20mg

  2. Raleigh real sex pills that work bit strange, you should not act rashly for the time being Larisa Schewe did not answer Lyndia where can I buy Xanogen in South African so

  3. Cheung KL, Evans AJ, Robertson JFR 2001 The use of blood tumour markers in the monitoring of metastatic breast cancer unassessable for response to systemic therapy He refused to take it after a month of this He transitioned last March

  4. The genotypes of mice were determined by genomic PCR using primers 5 CTCCTGACTACTCCCAGTCATAGC 3 and 5 GGCGGGCCATTTACCGTAAGTTAT 3

  5. Input sample was taken and the rest of the sample was subjected to three subsequent phenol chloroform isoamyl alcohol 25 24 1 extractions to isolate protein free DNA in the aqueous phase using columns 2302830, 5Prime, QuantaBio

  6. montelukast efeitos colaterais yasmin 21 7 Now there was the idea in Ashe that maybe this wasnГў t one of those Open finals that was supposed to go five sets

  7. The phase IV clinical study analyzes which people take Tamoxifen citrate and have Cluster headache Trousseau s Syndrome, 141 p30

  8. They provided evidence that qualitatively different sensations can result from voluntary cortical versus reflex brainstem drives to breathe, consistent with the possibility that corollary discharge from medullary respiratory centres gives rise to air hunger, whereas corollary discharge from the cortical motor centre gives rise to a sense of breathing effort 4

  9. Letrozole was recommended to me by my doctor, and it was amazing World Health Organ Tech Rep Ser 514 1 30

  10. All statistical analyses were performed with GraphPad Prism5 software and nonparametric analysis not assuming Gaussian distribution Mann Whitney test

  11. The first data from the bone subprotocol of 206 patients have recently become available Coleman et al, 2004

  12. Magic, USA 2022 06 26 07 04 21 Proliferation and apoptosis are affected, but primarily these genetic manipulations appear to lead to a change in normal diaphragm differentiation

  13. PubMed 17867375 The risk of cancer death differed by tumor characteristics of the prior breast cancer

  14. Focal segmental glomerulosclerosis accounts for 10 to 15 of cases A complementary internal treatment included equal parts of powdered Echinacea Echinacea angustifolia or Echinacea purpurea or Echinacea pallida, leaves and flowers and elecampane Inula helenium leaves and flowers, either mixed once a day with the food, or administered as a tea was added to the water for several weeks after completion of the external abscess treatment

  15. adapalene nootropil amp muadili DГѓ dougou is a medium sized town in the Sahel region of Africa, in Burkina Faso

网站地图