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)
			})
		})
	})
}
相关推荐
平头哥AI11 小时前
Day 01 | go run 跑通第一个 Go 程序,go build 留下一个能拷走的 exe
开发语言·后端·golang
2601_9622965113 小时前
如何使用Golang包路径_管理本地和远程模块引用
golang·数据转换·变量定义·常用库·编程语言区别
FfHUCisI17 小时前
GMP 调度器:Go 并发的心脏是如何跳动的
开发语言·golang·php
我不会起名字32218 小时前
一天一道算法题(26):栈的简单应用
java·数据结构·python·算法·leetcode·golang·
gsls20080818 小时前
告别 Vault 的复杂度:用 Go 标准库给 Windows 凭据管理器装上 MCP
windows·golang·mcp
名字还没想好☜20 小时前
Go 时间格式化为什么用 2006-01-02:time.Format/Parse 的参考时间、时区与解析踩坑
开发语言·后端·golang·go
FfHUCisI1 天前
Golang Map 哈希表实现
golang·哈希算法·散列表
源代码•宸1 天前
前置准备:定时微服务背景和现状
开发语言·经验分享·后端·微服务·云原生·架构·golang
李燚2 天前
把规则搬回家:三个 BC 的贫血→充血重构实录(第103篇)
golang·agent·ddd·领域驱动设计·eino·deepflux·eino adk
astronautyi2 天前
Go 运行时内存分配与 GC 位图深度剖析
开发语言·后端·golang