Go语言学习11-测试

Go语言学习11-测试

单元测试

go 复制代码
// functions.go
package testing

func square(op int) int {
	return op * op
}
go 复制代码
// functions_test.go
package testing

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

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])
		assert.Equal(t, expected[i], ret)
		//if ret != expected[i] {
		//	t.Errorf("input is %d, the expcted is %d, the actual %d",
		//		inputs[i], expected[i], ret)
		//}
	}
}

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")
}
内置单元测试框架
  • Fail, Error: 该测试失败, 该测试继续, 其他测试继续执行

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

  • 代码覆盖率

    bash 复制代码
    go test -v -cover
  • 断言https://github.com/stretchr/testify

Benchmark

go 复制代码
func BenchmarkConcatStringByAdd(b *testing.B) {
	// 与性能测试无关的代码
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		// 测试代码
	}
	b.StopTimer()
    // 与性能测试无关的代码
}
benchmark命令
bash 复制代码
go test -bench=. -benchmem

-bench=<相关benchmark测试>

Windows下使用go test命令行时, -bench=. 应写为 -bench="."

Behavior Driven Development

"I believe that the hardest part of software projects, the most common source of project failure, is communication with the customers and users of that software. By providing a clear yet precise language to deal with domains, a DSL can help improve this communication." -- Martin Fowler.

BDD in Go
项目网站

https://github.com/smartystreets/goconvey

安装
bash 复制代码
go get -u github.com/smartystreets/goconvey/convey
启动 web ui
bash 复制代码
$GOPATH/bin/goconvey
示例
go 复制代码
func TestSpec(t *testing.T) {
	// Only pass t into top-level Convey calls
	Convey("Given 2 even numbers", t, func() {
		a := 2
		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)
			})
		})
	})
}
相关推荐
zhuhezhang几秒前
go wails doctor提示Required dependencies missing: libwebkit
golang·wails·libwebkit
2501_941805313 小时前
使用Python和Go构建高性能分布式任务调度系统的实践分享
分布式·python·golang
有谁看见我的剑了?7 小时前
使用 go get github.com/go-sql-driver/mysql 驱动失败
golang
无心水7 小时前
2、Go语言源码文件组织与命令源码文件实战指南
开发语言·人工智能·后端·机器学习·golang·go·gopath
阿里云云原生8 小时前
阿里云可观测联合 Datadog 发布 OpenTelemetry Go 自动插桩工具
阿里云·golang·云计算·可观测
张丶大帅8 小时前
【走进Golang】
开发语言·后端·golang
无心水9 小时前
8、吃透Go语言container包:链表(List)与环(Ring)的核心原理+避坑指南
java·开发语言·链表·微服务·架构·golang·list
源代码•宸9 小时前
Golang原理剖析(Go语言垃圾回收GC)
经验分享·后端·算法·面试·golang·stw·三色标记
无心水9 小时前
6、Go语言类型判断与转换避坑指南:从类型断言到别名类型全解析
开发语言·后端·golang
且去填词9 小时前
并发模式(Patterns):Worker Pool 与 Pipeline 模式实现
golang·并发·数据流水线