Go语言学习笔记-测试

单元测试

  • t.Error()测试失败,后面的可以执行,其他测试继续执行
  • t.Fatal()测试失败,后面的不会执行,其它测试继续执行
package testing

import (
        "fmt"
        "testing"

        "github.com/stretchr/testify/assert"
)

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 expected is %d, the actual %d",
                                inputs[i], expected[i], ret)
                }
        }
}

func TestErrorInCode(t *testing.T) {
        fmt.Println("Start")
        t.Error("Error")
        fmt.Println("End")
}
func TestFailInCode(t *testing.T) {
        fmt.Println("Start")
        t.Fatal("Error")
        fmt.Println("End")
}

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)
        }
}

代码覆盖率 -cover
断言

benchmark

go test -bench=. -benchmem
> 方法名以Benchmark开头,参数testing.B
benchmem 打印内存分配次数

## bdd

你可能感兴趣的:(Go语言学习笔记-测试)