单元测试是质量保证十分重要的一环,好的单元测试不仅能及时地发现问题,更能够方便地调试,提高生产效率。所以很多人认为写单元测试是需要额外的时间,会降低生产效率,是对单元测试最大的偏见和误解。

go 语言原生支持了单元测试,使用上非常简单,测试代码只需要放到以 _test.go 结尾的文件中即可。golang 的测试分为单元测试性能测试,单元测试的测试用例以 Test 开头,性能测试以 Benchmark 开头。

举个例子

实现排列组合函数对应的单元测试和性能测试。

实现排列组合函数

// combination.go
package hmath
func combination(m, n int) int {
   if n > m-n {
       n = m - n
   }
   c := 1
   for i := 0; i < n; i++ {
       c *= m - i
       c /= i + 1
   }
   return c
}

实现单元测试和性能测试

// combination_test.go
package hmath
import (
   "math/rand"
   "testing"
)
// 单元测试
// 测试全局函数,以TestFunction命名
// 测试类成员函数,以TestClass_Function命名
func TestCombination(t *testing.T) {
   // 这里定义一个临时的结构体来存储测试case的参数以及期望的返回值
   for _, unit := range []struct {
       m        int
       n        int
       expected int
   }{
       {1, 0, 1},
       {4, 1, 4},
       {4, 2, 6},
       {4, 3, 4},
       {4, 4, 1},
       {10, 1, 10},
       {10, 3, 120},
       {10, 7, 120},
   } {
       // 调用排列组合函数,与期望的结果比对,如果不一致输出错误
       if actually := combination(unit.m, unit.n); actually != unit.expected {
           t.Errorf("combination: [%v], actually: [%v]", unit, actually)
       }
   }
}
// 性能测试
func BenchmarkCombination(b *testing.B) {
   // b.N会根据函数的运行时间取一个合适的值
   for i := 0; i < b.N; i++ {
       combination(i+1, rand.Intn(i+1))
   }
}
// 并发性能测试
func BenchmarkCombinationParallel(b *testing.B) {
   // 测试一个对象或者函数在多线程的场景下面是否安全
   b.RunParallel(func(pb *testing.PB) {
       for pb.Next() {
           m := rand.Intn(100) + 1
           n := rand.Intn(m)
           combination(m, n)
       }
   })
}

运行测试

go test combination_test.go combination.go           # 单元测试
go test --cover combination_test.go combination.go   # 单元测试覆盖率
go test -bench=. combination_test.go combination.go  # 性能测试

setup 和 teardown

setup 和 teardown 是在每个 case 执行前后都需要执行的操作,golang 没有直接的实现,可以通过下面这个方法实现全局的 setup 和 teardown,具体每个 case 的 setup 和 teardown 需要自己实现。

func TestMain(m *testing.M) {
   // setup code...
   os.Exit(m.Run())
   // teardown code...
}

goconvey

这个第三方工具会自动帮我们跑测试,并且以非常友好的可视化界面帮我们展示测试的结果,包括测试失败的原因,测试覆盖率等等,内部还提供了很多友好的断言,能提高测试代码的可读性

使用方法

func TestMain(m *testing.M) {
   // setup code...
   os.Exit(m.Run())
   // teardown code...
}

goconvey

这个第三方工具会自动帮我们跑测试,并且以非常友好的可视化界面帮我们展示测试的结果,包括测试失败的原因,测试覆盖率等等,内部还提供了很多友好的断言,能提高测试代码的可读性

使用方法

go get github.com/smartystreets/goconvey

然后用终端在测试代码的目录下运行 goconvey 命令即可

测试例子

package package_name
import (
   "testing"
   . "github.com/smartystreets/goconvey/convey"
)
func TestIntegerStuff(t *testing.T) {
   Convey("Given some integer with a starting value", t, func() {
       x := 1
       Convey("When the integer is incremented", func() {
           x++
           Convey("The value should be greater by one", func() {
               So(x, ShouldEqual, 2)
           })
       })
   })
}

参考链接

go testing: http://docs.studygolang.com/pkg/testing/

goconvey: https://github.com/smartystreets/goconvey

goconvey 文档: https://github.com/smartystreets/goconvey/wiki/Documentation

goconvey 标准断言: https://github.com/smartystreets/goconvey/wiki/Assertions

thumb_up

转载|出处:http://t.cn/RnvsFRp

Golang技术交流群:426582602

golang 单元测试的更多相关文章

  1. ARTS-S golang单元测试

    golang单元测试 在$GOPATH的src目录下建目录demo_unittest 在目录demo_unittest下建文件calc.go,内容如下: package demo_unittest f ...

  2. Golang单元测试框架整理

    目录 一.单元测试是什么 二.单元测试的意义 三.Golang单元测试框架 3.1 Golang内置testing包 3.1.1 简单的测试 3.1.2 Benchmark 基准测试 3.1.3 运行 ...

  3. golang单元测试

    使用testing进行单元测试 golang的测试库testing 测试文件与被测试文件在同一个包中 测试文件名为被测试文件名(去后缀)_test.go 测试用例函数以Test开头,TestFunc1 ...

  4. golang 单元测试&&性能测试

    一:单元测试 1.为什么要做单元测试和性能测试 减少bug 快速定位bug 减少调试时间 提高代码质量 2.golang的单元测试 单元测试代码的go文件必须以_test.go结尾 单元测试的函数名必 ...

  5. golang 单元测试(一)

    单元测试函数类型 Test(功能测试) 函数规则: 函数名: TestXxxx , 以Test为前缀.Xxxx以大写字母开头 参数类型: *testing.T func TestXxxx(t *tes ...

  6. golang单元测试简述

      Golang中内置了对单元测试的支持,不需要像Java一样引入第三方Jar才能进行测试,下面将分别介绍Golang所支持的几种测试: 一.测试类型   Golang中单元测试有功能测试.基准测试. ...

  7. golang单元测试一(简单函数测试)

    0.1.索引 https://blog.waterflow.link/articles/1663688140724 1.简介 单元测试是测试代码.组件和模块的单元函数.单元测试的目的是清除代码中的错误 ...

  8. 【GoLang】GoLang 单元测试、性能测试使用方法

    单元测试代码: ackage test import ( // "fmt" "testing" ) func Test_FlowControl(t *testi ...

  9. Golang 单元测试和性能测试

    开发程序其中很重要的一点是测试,我们如何保证代码的质量,如何保证每个函数是可运行,运行结果是正确的,又如何保证写出来的代码性能是好的,我们知道单元测试的重点在于发现程序设计或实现的逻辑错误,使问题及早 ...

随机推荐

  1. 13.56Mhz SI522兼容MFRC522的资料以及对比性能

    (13.56Mhz芯片) SI522是一颗专门替代MFRC522/FM17522,PIN对PIN 完全软硬件兼容.相对于MFRC522,SI522完全替换,不需要做任何更改,同时接受模式下功耗低10m ...

  2. 在Java中使用Maven配置的版本信息

    我们在使用maven开发一些项目的时候需要知道当前的版本状态,但版本状态储存在pom.xml文件中,可以采用以下2种方式进行获取: 1. 采用xml解析的方式去获取pom文件的{project.ver ...

  3. PAT——1048. 数字加密

    本题要求实现一种数字加密方法.首先固定一个加密用正整数A,对任一正整数B,将其每1位数字与A的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对13取余——这里用J代表10.Q代表11.K代 ...

  4. HDU 2307 贪心之活动安排问题

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2037 今年暑假不AC Time Limit: 2000/1000 MS (Java/Others)  ...

  5. lwip 2.0.3 DNS 域名解析 使用

    1.  在  lwipopts.h 中 #define LWIP_DNS 1 /* 使能 DNS 服务器的功能 ,2018年1月8日21:16:20,suozhang */ #define LWIP_ ...

  6. Gradle Goodness: Add Incremental Build Support to Tasks

    Gradle has a very powerful incremental build feature. This means Gradle will not execute a task unle ...

  7. zookeeper启动时报错:Error contacting service. It is probably not running问题

    查看zookeeper.out发现启动日志报错未找到java路径. 启动日志位于zookeeper-4.0.10/bin目录下 修改/etc/profile中环境变量得以解决.

  8. AutoMapper 帮助类

    AutoMapper帮助类 /// <summary> /// AutoMapper帮助类 /// </summary> public static class AutoMap ...

  9. Java 8-Stream流

    出处:Java 8 中的 Stream API详解 什么是流 Stream 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的,它更像一个高级版本的 Iterator.原始版本的 Iter ...

  10. 通过系统进程查找sql语句

    一.通过系统进程id查找sql语句 SELECT /*+ ORDERED */ sql_text FROM v$sqltext a WHERE (a.hash_value, a.address) IN ...