传统测试
-
测试数据与测试逻辑混在一起
-
出错信息不明确
-
一旦一个数据出错,测试全部结束
@Test public void testAdd() { assertEquals(3, add(1, 2)); assertEquals(2, add(0, 2)); assertEquals(0, add(0, 0)); assertEquals(0, add(-1, 1)); assertEquals(Integer.MIN_VALUE, add(1, Integer.MAX_VALUE)); }
表格驱动测试
-
测试数据与测试逻辑分离
-
明确的出错信息(自定义出错信息内容)
-
可以部分失败
func calcTriangle(a, b int) int { var c int c = int(math.Sqrt(float64(a*a + b*b))) return c } tests := []struct{ a, b, c int }{ {3, 4, 5}, {5, 12, 13}, {8, 15, 17}, {12, 35, 37}, {30000, 40000, 50000}, } for _, tt := range tests { if actual := calcTriangle(tt.a, tt.b); actual != tt.c { t.Errorf("calcTriangle(%d, %d); "+ "got %d; expected %d", tt.a, tt.b, actual, tt.c) } }
testing.T的使用
testing.B的使用
代码覆盖
-
使用go test生成代码覆盖报告
go test -couverprofile=test.prof
-
使用go tool cover查看代码覆盖报告
go tool cover -html=test.prof
http测试
Web应用程序中往往需要与其他系统进行交互,比如通过http访问其他系统,此时就需要有一种方法用于打桩来模拟Web服务器和客户端,httptest包即Go语言针对Web应用提供的解决方案
测试方式
- 通过使用假的Request/Response
- 通过起服务器
文档
-
用注释写文档
package queue // A FIFO queue. type Queue []int // Pushes the element into the queue. // e.g. q.Push(123) func (q *Queue) Push(v int) { *q = append(*q, v) } // Pops element from head. func (q *Queue) Pop() int { head := (*q)[0] *q = (*q)[1:] return head } // Returns if the queue is empty or not. func (q *Queue) IsEmpty() bool { return len(*q) == 0 }
-
在测试中加入Example
package queue import "fmt" 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 }
在文档中可以查看到如下内容
-
使用go doc查看文档
go doc Queue type Queue []int A FIFO queue. func (q *Queue) IsEmpty() bool func (q *Queue) Pop() int func (q *Queue) Push(v int) go doc Queue.isEmpty func (q *Queue) IsEmpty() bool Returns if the queue is empty or not.
-
使用godoc生成文档()
godoc -http :6060
访问 http://127.0.0.1:6060 可以查看到如下文档