
Go单元测试
单元测试 - 单个
- 创建测试文件:测试文件通常与被测试的代码文件在同一目录下,并以_test.go结尾。例如,如果你有一个名为calculator.go的文件,那么测试文件应该命名为calculator_test.go
- 编写测试函数:测试函数的名称必须以Test开头,后接一个首字母大写的字符串(通常是被测试函数的名称)。
- 运行测试:使用go test命令运行测试
假设我们有一个calculator.go
文件,内容如下:
go
package calculator
func Add(a, b int) int {
return a + b
}
func Subtract(a, b int) int {
return a - b
}
然后,我们创建calculator_test.go
文件,编写测试:
go
package calculator
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
expected := 5
if result != expected {
t.Errorf("Add(2, 3) = %d; expected %d", result, expected)
}
}
func TestSubtract(t *testing.T) {
result := Subtract(5, 3)
expected := 2
if result != expected {
t.Errorf("Subtract(5, 3) = %d; expected %d", result, expected)
}
}
测试单例
shell
go test -v
结果
text
PS E:\go_ws\demo> go test -v
=== RUN TestAdd
--- PASS: TestAdd (0.00s)
=== RUN TestSubtract
--- PASS: TestSubtract (0.00s)
PASS
ok demo2 0.036s
单元测试 -- 多个
下面演示下如何多次单侧, 其实就是利用map循环来实现的
main.go
go
package main
// 被测试的函数:字符串反转
func ReverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
main_test.go
go
package main
import "testing"
// 测试字符串反转函数
func TestReverseString(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"hello", "olleh"},
{"world", "dlrow"},
{"", ""},
{"a", "a"},
{"你好世界", "界好世你"},
}
for _, test := range tests {
result := ReverseString(test.input)
if result != test.expected {
t.Errorf("ReverseString(%s) = %s; expected %s", test.input, result, test.expected)
}
}
}