介绍
今天就跟大家聊聊有关利用golang怎么实现单元测试,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
<强>单元测试强>
单元测试的格式形如:
func TestAbs (t * testing.T), { ,got :=, Abs (1) ,if got  !=, 1, { t.Errorf才能(“Abs (1),=, % d;, want 1“,,,有) ,} }
在util目录下创建一个文件util_test。去,添加一个单元测试:
package 实效 import “testing"//,普通的测试 func TestGenShortID (t * testing.T), { ,shortID, err :=, GenShortID () ,if shortID ==,““, | |, err !=, nil { ,t.Error (“GenShortID failed") ,} }
然后,在根目录下运行测试- v。/util/,测试结果如下:
root@592402321ce7: #/工作区,go test -v 。/util/===,RUN TestGenShortID ——作用;通过:TestGenShortID (0.00秒) 通过 ok ,;tzh.com/web/util ,,,, 0.006年代
<>强性能测试强>
性能测试的结果形如:
func BenchmarkHello (b * testing.B), { ,for 小姐::=,0;,小姐:& lt;, b.N;,我+ +,{ fmt.Sprintf才能(“hello") ,} }
在util_test。去添加性能测试:
//,性能测试 func BenchmarkGenShortID (b * testing.B), { ,for 小姐::=,0;,小姐:& lt;, b.N;,我+ +,{ ,GenShortID () ,} }
运行结果如下(使用——运行=没有避免运行普通的测试函数,因为一般不可能有函数名匹配none):
root@592402321ce7: #/工作区,go test -v 板凳=癇enchmarkGenShortID“美元——=none 运行。/util/美好的:linux goarch: amd64 包裹:;tzh.com/web/util BenchmarkGenShortID-2 ,,,,,, 507237,,,,,,, 2352, ns/op 通过 时间,ok ;tzh.com/web/util ,,, 1.229年代
这说明,平均每次运行GenShortID()需要2352纳秒。
<>强性能分析强>
运行测试的时候,可以指定一些参数,生成性能文件资料。
-blockprofile block.out Write 才能a goroutine  blocking profile 用,specified 文件 when 才能all tests 断开连接,完成。 Writes 才能;test  binary as -c 。 -blockprofilerate n Control 才能;从而,detail provided 拷贝goroutine blocking profiles 通过 calling 才能;runtime.SetBlockProfileRate  with n。 阅读才能& # 39;go doc runtime.SetBlockProfileRate& # 39;。 从而才能profiler aims 用样品,,,,,one blocking event 每一个 n 才能;nanoseconds 从而program spends 阻塞只By 默认情况下, if 才能-test.blockprofile is  set without 却;能够国旗,all blocking 事件 断开连接,才能记录,equivalent 用-test.blockprofilerate=1。 -coverprofile cover.out Write 才能a coverage  profile 用,file after all tests have 通过。 ,Sets 覆盖。 -cpuprofile cpu.out Write 才能a CPU  profile 用,specified file before 退出。 Writes 才能;test  binary as -c 。 -memprofile mem.out Write 才能an allocation  profile 用,file after all tests have 通过。 Writes 才能;test  binary as -c 。 -memprofilerate n Enable 才能;more  precise (以及昂贵),memory allocation profiles 通过 setting 才能runtime.MemProfileRate只阅读& # 39;go doc runtime.MemProfileRate& # 39;。 用才能profile all  memory 分配,use -test.memprofilerate=1。 -mutexprofile mutex.out Write 才能a mutex  contention profile 用,specified 文件 when 才能all tests 断开连接,完成。 Writes 才能;test  binary as -c 。 -mutexprofilefraction n Sample 1,才能拷贝n stack traces of goroutines holding contended 才能,互斥锁。利用golang怎么实现单元测试