Go-单元测试

目录

一、单元测试

1、表格测试

2、内置单元测试框架

a、显示代码覆盖率

b、断言

二、Benchmark

1、用途

2、benchmark代码的格式

3、benchmark示例

a、benchmark测试命令

b、go test -bench=. -benchmen

三、BDD

1、什么是BDD

2、BDD的格式

3、BDD in Go

a、goconvey

b、安装

c、代码示例

d、启动 web UI

四、总结


一、单元测试

1、表格测试

表格测试,就是我们用一组输入值,然后在定义一组期望值,看程序运行结果和期望值是否一致。

package unit_test

import "testing"

//平方
func square(num int) int {
	return num * num
}

//表格测试法
func TestSquare(t *testing.T)  {
	//输入值
	inputs := [...]int{1, 2, 3}
	//期望值
	expected := [...]int{1, 4, 9}

	for i := 0; i< len(inputs); i++ {
		ret := square(inputs[i])
		if ret != expected[i] {
			t.Errorf("intput is %d, the expected is %d, the actual is %d", inputs[i], expected[i], ret)
		}
	}
}

2、内置单元测试框架

  • Fail, Error :若该测试失败,该测试会继续往下执行,但是不会影响其它测试任务的执行;
  • FailNow,Fatal:若该测试失败,则该测试会终止,其它测试任务还是可以继续执行。
package unit_test

import (
	"fmt"
	"testing"
)

//Error 不会中断当前测试程序
func TestErrorInCode(t *testing.T){
	fmt.Println("Start")
	t.Error("Error")
	fmt.Println("End")
}
/*
=== RUN   TestErrorInCode
Start
functions_test.go:31: Error
End
--- FAIL: TestErrorInCode (0.00s)
FAIL
*/


//Fatal 会中断当前测试程序
func TestFatalInCode(t *testing.T) {
	fmt.Println("Start")
	t.Fatal("Fatal")
	fmt.Println("End")
}

/*
=== RUN   TestFatalInCode
Start
functions_test.go:47: Fatal
--- FAIL: TestFatalInCode (0.00s)
FAIL
*/

a、显示代码覆盖率

go test -v -cover

b、断言

https://github.com/stretchr/testify
package unit_test

import (
	"fmt"
	"github.com/stretchr/testify/assert"
	"testing"
)

//平方
func square(num int) int {
	return num * num
}

//表格测试法
func TestSquare(t *testing.T) {
	//输入值
	inputs := [...]int{1, 2, 3}
	//期望值
	expected := [...]int{2, 4, 9}

	for i := 0; i< len(inputs); i++ {
		ret := square(inputs[i])
		//调用 assert 断言包
		assert.Equal(t, expected[i], ret)
	}
}

二、Benchmark

1、用途

  • 对程序中某些代码片段的进行一个性能测评,比较一下哪种写法会更好一些。
  • 对第三方库进行一个测评,看哪个库性能更好一些。

2、benchmark代码的格式

//benchmark 代码格式
func BenchmarkCode(b *testing.B){

	//与性能测试无关的代码的开始位置
	b.ResetTimer()

    //性能测试交给 framework 来做,将需要测试的代码放在循环中,
    //循环的次数由 framework 来返回
	for i := 0; i < b.N; i++ {
		//被测试性能的代码
	}

	//与性能测试无关代码的结束为止
	b.StopTimer()
}
  • 方法名以 Benchmark 开头;
  • 参数类型是 *testing.B
  • b.ResetTimer( ) b.StopTimer() 来隔离与性能测试无关的代码;
  • 性能测试交给 framework 来做,将需要测试的代码放在循环中,循环的次数由 framework 来返回。

3、benchmark示例

package benchmark

import (
	"bytes"
	"testing"
)

//通过字符串连接的方式拼接字符串
func ConcatStringByLink() string {
	elements := [...]string{"a", "b", "c", "d"}
	str := ""
	for _, elem := range elements {
		str += elem
	}

	return str
}


func ConcatStringByBytesBuffer() string {
	elements := [...]string{"a", "b", "c", "d"}
	var buf bytes.Buffer

	for _, elem := range elements {
		buf.WriteString(elem)
	}

	return buf.String()
}

//用benchmark测试字符串拼接方法的性能
func BenchmarkConcatStringWithLink(b *testing.B){
	//与性能测试无关的代码的开始位置
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		ConcatStringByLink()
	}

	//与性能测试无关代码的结束为止
	b.StopTimer()
}

//用 benchmark 测试 bytes.buffer 连接字符串的性能
func BenchmarkConcatStringWithByteBuffer(b *testing.B){
	//与性能测试无关的代码的开始位置
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		ConcatStringByBytesBuffer()
	}

	//与性能测试无关代码的结束为止
	b.StopTimer()
}


/*
方法名											代码运行次数				单次运行时间
BenchmarkConcatStringWithLink-12                10782126               100.3 ns/op
BenchmarkConcatStringWithByteBuffer-12          17448060                68.47 ns/op
*/

方法名代码运行此时单词运行时间
BenchmarkConcatStringWithLink-12 10782126100.3 ns/op
BenchmarkConcatStringWithByteBuffer-121744806068.47 ns/op

a、benchmark测试命令

//-bench= 后面跟方法名,如果是所有方法就写"."
go test -bench=.

注意:windows下使用 go test 命令时, -bench=.应该写成 -bench="."

b、go test -bench=. -benchmen

如果想知道 代码每一次的内存分配情况,这种方案为什么快,那种方案为什么慢,可以加一个 -benchmen 参数。

go test -bench=. -benchmen

三、BDD

1、什么是BDD

BDD(Behavior Driven Development),行为驱动开发。

为了让我们和客户间的沟通更加顺畅,我们会用同一种”语言“来描述一个系统,避免表达不一致的问题,当出现了什么行为,会出现什么结果。

2、BDD的格式

Given-When -Then

3、BDD in Go

a、goconvey

https://github.com/smartystreets/goconvey

b、安装

go get -u github.com/smartystreets/goconvey

c、代码示例

package bdd_spec

import (
	"testing"
	//前面这个点,表示将 import 进来的 package 的方法是在当前名字空间的,可以直接使用里面的方法。
	//例如使用 So()方法,就可以直接用,不用写成 convey.So()
	. "github.com/smartystreets/goconvey/convey"
)

//BDD框架 convey的使用
func TestSpec(t *testing.T)  {
	Convey("Given 2 even numbers", t, func() {
		a := 3
		b := 4

		Convey("When add the two numbers", func() {
			c := a + b

			Convey("Then the result is still even", func() {
				So(c%2, ShouldEqual, 0)
			})
		})
	})
}

d、启动 web UI

$GOPATH/bin/goconvey

 如果端口冲突了,可以这样解决

$GOPATH/bin/goconvey -port 8081

四、总结

  • 表格测试,就是我们用一组输入值,然后在定义一组期望值,看程序运行结果和期望值是否一致。
  • Error :若该测试失败,该测试会继续往下执行,但是不会影响其它测试任务的执行;
  • Fatal:若该测试失败,则该测试会终止,其它测试任务还是可以继续执行。
  • 显示代码覆盖率:go test -v -cover
  • assert断言:https://github.com/stretchr/testify 。
  • 方法名以 Benchmark 开头;
  • 参数类型是 *testing.B
  • b.ResetTimer( ) b.StopTimer() 来隔离与性能测试无关的代码;
  • 性能测试交给 framework 来做,将需要测试的代码放在循环中,循环的次数由 framework 来返回;
  • benchmark测试命令:go test -bench=.
  • benchmark查看内存使用情况:go test -bench=. -benchmen 。
  • BDD(Behavior Driven Development),行为驱动开发;
  • goconveyhttps://github.com/smartystreets/goconvey
  • 启动 goconvey 的webUI:$GOPATH/bin/goconvey

:这篇博文是我学习中的总结,如有转载请注明出处:

https://blog.csdn.net/DaiChuanrong/article/details/118667975

上一篇Go-并发任务

下一篇Go-反射编程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值