示例代码请访问:github.com/wenjianzhan…
单元测试
functions.go
package testing
func square(op int) int {
return op * op
}
functions_test.go
package testing
import "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])
if ret != expected[i] {
t.Errorf("input is %d, the exoected is %d, the actual %d", inputs[i], expected[i], ret)
}
}
}
输出
=== RUN TestSquare
--- PASS: TestSquare (0.00s)
PASS
Process finished with exit code 0
这里输出结果是正确的,和预期是一样的
内置单元测试框架
- Fail, Error: 该测试失败,该测试继续,其他测试继续执行
- FailNow, Fatal: 该测试失败,该测试中止,其他测试继续执行
- 代码覆盖率 go test -v -cover
- 断言 github.com/stretchr/te…
Fail, Error
func TestErrorInCode(t *testing.T) {
fmt.Println("start")
t.Error("Error")
fmt.Println("End")
}
输出
=== RUN TestErrorInCode
start
End
--- FAIL: TestErrorInCode (0.00s)
functions_test.go:22: Error
FAIL
Process finished with exit code 1
FailNow, Fatal
func TestFailInCode(t *testing.T) {
fmt.Println("start")
t.Fatal("Fail")
fmt.Println("End")
}
输出
=== RUN TestFailInCode
start
--- FAIL: TestFailInCode (0.00s)
functions_test.go:28: Fail
FAIL
Process finished with exit code 1
断言
func TestSquareWithAssert(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 exoected is %d, the actual %d", inputs[i], expected[i], ret)
}
}
}
输出
=== RUN TestSquareWithAssert
--- PASS: TestSquareWithAssert (0.00s)
PASS
Process finished with exit code 0
示例代码请访问:github.com/wenjianzhan…