zoukankan      html  css  js  c++  java
  • go单元测试

    testing模块

    • 测试代码放在当前包以_test.go结尾的文件中
    • 测试函数以Test为名称前缀
    • 测试命令(go test)
    • 正常编译操作(go build/install)会忽略测试文件

    单例模式举例

    singleton.go

    package singleton
    
    import (
    	"sync"
    )
    
    type Singleton struct{}
    
    var (
    	singleton *Singleton
    	once      sync.Once
    )
    
    func GetInstance() *Singleton {
    	once.Do(func() {
    		singleton = &Singleton{}
    	})
    	return singleton
    }
    

      

    singleton_test.go

    package singleton
    
    import "testing"
    
    func TestSingleton(t *testing.T) {
    	ins1 := GetInstance()
    	ins2 := GetInstance()
    	if ins1 != ins2 {
    		t.Fatal("instance is not equal")
    	}
    }
    

      

    终端执行go test,会执行singleton_test.go里面写的测试用例

    D:projectsrcgo_devdesign_patternsingleton>go test
    PASS
    ok      go_dev/design_pattern/singleton 0.346s
    

      

    查看测试代码覆盖率

    go test -coverprofile=c.out
    go tool cover -html=c.out

      

    输出

    D:projectsrcgo_devdesign_patternsingleton>go test -coverprofile=c.out
    PASS
    coverage: 100.0% of statements
    ok      go_dev/design_pattern/singleton 0.324s
    

      

    性能测试(_test.go)

    func BenchSingleton(b *testing.B) {
    	ins1 := GetInstance()
    	ins2 := GetInstance()
    	for i := 0; i < b.N; i++ {
    		if ins1 != ins2 {
    			b.Fatal("instance is not equal")
    		}
    	}
    }
    

      

    执行

    go test -bench .
    

      

    分析性能

    D:projectsrcgo_devdesign_patternsingleton>go test -bench . -cpuprofile cpu.out
    D:projectsrcgo_devdesign_patternsingleton>go tool pprof cpu.out
    Type: cpu
    Time: Aug 23, 2018 at 11:33am (CST)
    Duration: 200ms, Total samples = 0
    Entering interactive mode (type "help" for commands, "o" for options)
    (pprof) web
    

      

      

  • 相关阅读:
    java快速排序代码
    java操作redis实现和mysql数据库的交互
    python 操作mysql数据库存
    JAVA 操作远程mysql数据库实现单表增删改查操作
    URI和URL及URN的区别
    day06_字符集设置
    day6_oracle手工建库
    day08_SGA后半部分
    day08_存储
    day05_sqlloader基础
  • 原文地址:https://www.cnblogs.com/hongpeng0209/p/9522508.html
Copyright © 2011-2022 走看看