Golang
测试
转换一下心情,来尝试看看单元测试好了
在golang上要跑测试的话,可以考虑先试看看内建 testing 套件。
首先,我们需要先import testing,之後跟很多单元测试雷同,我们需要让function name做点变化,func TestXxx
大致上需要注意以下的几个规则
先来看 The Go Playground的test 范例,原版是下面这样
package main
import (
"testing"
)
// LastIndex returns the index of the last instance of x in list, or
// -1 if x is not present. The loop condition has a fault that
// causes somes tests to fail. Change it to i >= 0 to see them pass.
func LastIndex(list []int, x int) int {
for i := len(list) - 1; i > 0; i-- {
if list[i] == x {
return i
}
}
return -1
}
func TestLastIndex(t *testing.T) {
tests := []struct {
list []int
x int
want int
}{
{list: []int{1}, x: 1, want: 0},
{list: []int{1, 1}, x: 1, want: 1},
{list: []int{2, 1}, x: 2, want: 0},
{list: []int{1, 2, 1, 1}, x: 2, want: 1},
{list: []int{1, 1, 1, 2, 2, 1}, x: 3, want: -1},
{list: []int{3, 1, 2, 2, 1, 1}, x: 3, want: 0},
}
for _, tt := range tests {
if got := LastIndex(tt.list, tt.x); got != tt.want {
t.Errorf("LastIndex(%v, %v) = %v, want %v", tt.list, tt.x, got, tt.want)
}
}
}
我们来改个版本看看
package main
import (
"testing"
)
// LastIndex returns the index of the last instance of x in list, or
// -1 if x is not present. The loop condition has a fault that
// causes somes tests to fail. Change it to i >= 0 to see them pass.
func LastIndex(list []int, x int) int {
for i := len(list) - 1; i > 0; i-- {
if list[i] == x {
return i
}
}
return -1
}
func TestLastIndex(t *testing.T) {
tests := []struct {
list []int
x int
want int
}{
{list: []int{1}, x: 1, want: -1},
{list: []int{1, 1}, x: 1, want: 1},
{list: []int{2, 1}, x: 2, want: -1},
{list: []int{1, 2, 1, 1}, x: 2, want: 1},
{list: []int{1, 1, 1, 2, 2, 1}, x: 3, want: -1},
{list: []int{3, 1, 2, 2, 1, 1}, x: 3, want: -1},
}
for _, tt := range tests {
if got := LastIndex(tt.list, tt.x); got != tt.want {
t.Errorf("LastIndex(%v, %v) = %v, want %v", tt.list, tt.x, got, tt.want)
}
}
}
这样跑我们就可以得到PASS,就是验证都符合我们要的结果,那如果跑回原本的CASE,则会出现FAIL。
参考资料
https://pkg.go.dev/testing
https://play.golang.org/
<<: 新新新手阅读 Angular 文件 - Component - Day24
以下笔记摘录自『 The Go Workshop 』。 列举 列举是一种定义一系列常数的方式,常数是...
第3话 Agile 汇出 Part & BOM(1) 想要汇出Agile的Part与BOM,...
前言 今天是铁人赛的第22天,接下来几天的文章应该都是当天写完当天上传的ON档状态 一不小心就会开天...
昨天的文章中已介绍火焰粒子的制作,那麽今天的文章将会说明如何在AR世界中产生火焰! 火焰产生器 在场...
Skipfish 是一个主动的Web应用程序安全测试工具 透过执行递归爬网和基於字典的探测 易於使用...