Go 学习之 测试函数编写与文档记录

功能函数

// queue.go

package queue

// Queue :  A FIFO queue.
type Queue []int

// Push : Pushes the element into the queue.
// 		e.g. q.Push(123)
func (q *Queue) Push(v int) {
	*q = append(*q, v)
}

// Pop : Pops element from head.
func (q *Queue) Pop() int {
	head := (*q)[0]
	*q = (*q)[1:]
	return head
}

// IsEmpty : Returns if the queue is empty or not.
func (q *Queue) IsEmpty() bool {
	return len(*q) == 0
}

测试函数

注意点!

  1. 文件命名方式 (原文件名)_test.go
  2. Test 函数命名方式 Test(待测试函数名),参数 t *testing.T
  3. Benchmark 测试函数(测试性能) 参数 b *testing.B
  4. Example 测试函数,期望结果【通过注释方式,以 Output 开头】
// queue_test.go 
// 注意文件命名方式,后面加 _test

package queue

import (
	"fmt"
	"testing"
)

// 注意函数命名方式  Example 函数
// Output 写自己期望的输出
func ExampleQueue_Pop() {
	q := Queue{1}
	q.Push(2)
	q.Push(3)
	fmt.Println(q.Pop())
	fmt.Println(q.Pop())
	fmt.Println(q.IsEmpty())

	fmt.Println(q.Pop())
	fmt.Println(q.IsEmpty())

	// Output:
	// 1
	// 2
	// false
	// 3
	// true
}

// 表格测试函数:数据与测试逻辑分离
// 注意函数命名方式 Test 函数  
// 参数 t *testing.T
// Benchmark 测试函数是测试性能,此处没有写,参数为  b *testing.B
func TestQueue_Pop(t *testing.T) {
	data := []struct {
		example Queue
		expect  int
	}{
		{[]int{1, 2, 3}, 1},
		{[]int{2, 35, 4}, 2},
	}

	for _, tt := range data {
		actual := tt.example.Pop()
		if actual != tt.expect {
			t.Errorf("Expect: %d, Actual: %d, Error!", tt.expect, actual)
		}
	}
}

文档记录

go doc 查看

# 不加参数,会打印当前包中的数据结构
$ go doc                             
package queue // import "queue"

type Queue []int

# 可以指定函数,将会打印此函数的介绍信息(就是函数功能的注释信息)
# 可以通过更改此函数的注释,改变打印的内容
$ go doc Pop                                                                   
package queue // import "."

func (q *Queue) Pop() int
    Pop : Pops element from head.

godoc 网页查看

优势:

  • 不仅可以展示 go get 下载的包
  • 而且自己编写的函数,也会以文档形式展示,见下面截图
# 首先下载包
$  go get golang.org/x/tools/cmd/godoc

# 开启端口进行展示  指定了 6060 端口
$ godoc -http=:6060

# 访问 
localhost:6060
注释形成的文档形式

在这里插入图片描述

Example 形成的文档形式

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值