Go语言学习11-测试

本文介绍了在Go语言中进行单元测试的方法,包括使用`testing`包进行基本测试和错误处理,以及使用第三方库如`assert`进行断言。此外,还提及了行为驱动开发(BDD)的实践,如GoConvey库的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Go语言学习11-测试

单元测试

// functions.go
package testing

func square(op int) int {
	return op * op
}
// 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: 该测试失败, 该测试中止, 其他测试继续执行

  • 代码覆盖率

    go test -v -cover
    
  • 断言https://github.com/stretchr/testify

Benchmark

func BenchmarkConcatStringByAdd(b *testing.B) {
	// 与性能测试无关的代码
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		// 测试代码
	}
	b.StopTimer()
    // 与性能测试无关的代码
}
benchmark命令
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

安装
go get -u github.com/smartystreets/goconvey/convey
启动 web ui
$GOPATH/bin/goconvey
示例
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)
			})
		})
	})
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

残魁斜罡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值