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
    

      

      

  • 相关阅读:
    多种语言求n的阶乘
    (转)Bullet 物理引擎 简析[1]
    (转)Bullet 引擎 详解 DBVT 分析
    (转载)C Runtime Library(MSVCRT)来历
    (转)角色蒙皮
    计算两向量的旋转角(转)
    lua中文教程(第二章 类型和值)
    lua中文教程(第一章 起点)
    (转)Bullet 引擎 详解 碰撞事件 回调函数
    (转)Bullet 3D 物理引擎 简析(2)
  • 原文地址:https://www.cnblogs.com/hongpeng0209/p/9522508.html
Copyright © 2011-2022 走看看