Go语言学习笔记-测试

2019-04-30  本文已影响0人  noonenote

单元测试

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
上一篇下一篇

猜你喜欢

热点阅读