• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Go测试

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

单元测试

命令:go test -v -cover

表格单元测试

被测试函数

package unit

func Square(n int) int {
	return n * n
}

表格测试编写

package unit

import "testing"

func TestSquare(t *testing.T) {
	inputs := [...]int{1,2,3}
	expected := [...]int{1,4,9}
	for i,v := range inputs{
		if Square(v) != expected[i]{
			t.Errorf("Input is %d, the expected is %d, the actual %d", v, expected[i], expected[i])
		}
	}
}

关键字

  • Fail, Error: 该测试失败,该测试继续,其他测试继续执行
  • FailNow, Fatal: 该测试失败,该测试中止,其他测试继续执行
package unit

import (
	"fmt"
	"testing"
)

func TestErrorInCode(t *testing.T)  {
	fmt.Println("Start")
	t.Error("Error")
	fmt.Println("End")
}

func TestFailInCode(t *testing.T)  {
	fmt.Println("Start")
	t.Fatal("Error")
	fmt.Println("End")
}

性能测试

命令(运行所有):go test -bench=.
命令(运行指定):go test -bench=BenchmarkConcatStringByAdd
命令(详细比较):go test -bench=. -benchmem

写法

func BenchmarkConcatStringByAdd(b *testing.B){
    // 与性能测试无关的代码
    b.ResetTimer()
    for i:=0; i<b.N;i++{
        // 测试代码
    }
    // 与性能测试无关的代码
    b.StopTimmer()
}

示例

package benchmark

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

func TestConcatStringByAdd(t *testing.T) {
	assert := assert.New(t)
	elems := []string{"1", "2", "3", "4", "5"}
	ret := ""
	for _, elem := range elems {
		ret += elem
	}
	assert.Equal("12345", ret)
}

func TestConcatStringByBytesBuffer(t *testing.T) {
	assert := assert.New(t)
	var buf bytes.Buffer
	elems := []string{"1", "2", "3", "4", "5"}
	for _, elem := range elems {
		buf.WriteString(elem)
	}
	assert.Equal("12345", buf.String())
}

func BenchmarkConcatStringByAdd(b *testing.B) {
	elems := []string{"1", "2", "3", "4", "5"}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		ret := ""
		for _, elem := range elems {
			ret += elem
		}
	}
	b.StopTimer()
}

func BenchmarkConcatStingByBytesBuffer(b *testing.B) {
	elems := []string{"1", "2", "3", "4", "5"}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		var buf bytes.Buffer
		for _, elem := range elems {
			buf.WriteString(elem)
		}
	}
	b.StopTimer()
}

BDD

BDD(Behavior Driven Development),直译是行为驱动开发,主要是为了解决验收功能的业务人员与开发人员之间的沟通问题

package BDD

import (
	. "github.com/smartystreets/goconvey/convey"
	"testing"
)

func TestSpec(t *testing.T) {

	// Only pass t into top-level Convey calls
	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)
			})
		})
	})
}

详细使用点这里


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
(Go)13.判断文件或者目录是否存在发布时间:2022-07-10
下一篇:
this.$router.push、replace、go的区别发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap