go test 测试用例那些事

  go test命令,相信大家都不陌生,常见的情况会使用这个命令做单测试、基准测试和http测试。go test还是有很多flag 可以帮助我们做更多的分析,比如测试覆盖率,cpu分析,内存分析,也有很多第三方的库支持test,cpu和内存分析输出结果要配合pprof和go-torch来进行可视化显示,可以看一下之前的这篇帖子 

func TestXXXXXXX(t *testing.T) func BenchXXXXXX(b *testing.B) func TestMain(m *testing.M)
复制代码

    看一下testing.T和testing.B者有组合 common

复制代码
type T struct {     common     isParallel bool     context    *testContext // For running tests and subtests.}
复制代码
复制代码
type B struct {     common     importPath       string // import path of the package containing the benchmark    context          *benchContext     N                int     previousN        int           // number of iterations in the previous run    previousDuration time.Duration // total duration of the previous run    benchFunc        func(b *B)     benchTime        time.Duration     bytes            int64     missingBytes     bool // one of the subbenchmarks does not have bytes set.    timerOn          bool     showAllocResult  bool     result           BenchmarkResult     parallelism      int // RunParallel creates parallelism*GOMAXPROCS goroutines     // The initial states of memStats.Mallocs and memStats.TotalAlloc.    startAllocs uint64     startBytes  uint64     // The net total of this test after being run.    netAllocs uint64     netBytes  uint64 }
复制代码

    common包含了T和B的所有公共方法,常见的比如Log()日志信息,Error() 错误信息,Fail()致命错误等方法,

    TestMain(*testing.M)方法有些特殊,在一个包内只能有一个TestMain方法。这个方法会在测试方法运行前调用,相当于main()方法。我们可以在这个方法内做一些初始化数据操作等。看一下testing.M结构体

复制代码
// M is a type passed to a TestMain function to run the actual tests.type M struct {     deps       testDeps     tests      []InternalTest     benchmarks []InternalBenchmark     examples   []InternalExample      timer     *time.Timer     afterOnce sync.Once      numRun int }
复制代码

   专为TestMain准备

    先以app1来对基本的test进行解说,app1的项目结构为。

     具体的代码大家看一下就好,都是一些特别简单的方法。

测试指定函数

    简单的测试方法

关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信