Go测试

单元测试

命令:go test -v -cover

表格单元测试

被测试函数

package unit

func Square(n int) int {
    return n * n
}

表格测试编写

package unit

import "testing"

func TestSquare(t *testing.T) {
    inputs := [...]int{1,2,3}
    expected := [...]int{1,4,9}
    for i,v := range inputs{
        if Square(v) != expected[i]{
            t.Errorf("Input is %d, the expected is %d, the actual %d", v, expected[i], expected[i])
        }
    }
}

关键字

  • Fail, Error: 该测试失败,该测试继续,其他测试继续执行
  • FailNow, Fatal: 该测试失败,该测试中止,其他测试继续执行
package unit

import (
    "fmt"
    "testing"
)

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

性能测试

命令(运行所有):go test -bench=.
命令(运行指定):go test -bench=BenchmarkConcatStringByAdd
命令(详细比较):go test -bench=. -benchmem

写法

func BenchmarkConcatStringByAdd(b *testing.B){
    // 与性能测试无关的代码
    b.ResetTimer()
    for i:=0; i<b.N;i++{
        // 测试代码
    }
    // 与性能测试无关的代码
    b.StopTimmer()
}

示例

package benchmark

import (
    "bytes"
    "github.com/stretchr/testify/assert"
    "testing"
)

func TestConcatStringByAdd(t *testing.T) {
    assert := assert.New(t)
    elems := []string{"1", "2", "3", "4", "5"}
    ret := ""
    for _, elem := range elems {
        ret += elem
    }
    assert.Equal("12345", ret)
}

func TestConcatStringByBytesBuffer(t *testing.T) {
    assert := assert.New(t)
    var buf bytes.Buffer
    elems := []string{"1", "2", "3", "4", "5"}
    for _, elem := range elems {
        buf.WriteString(elem)
    }
    assert.Equal("12345", buf.String())
}

func BenchmarkConcatStringByAdd(b *testing.B) {
    elems := []string{"1", "2", "3", "4", "5"}
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        ret := ""
        for _, elem := range elems {
            ret += elem
        }
    }
    b.StopTimer()
}

func BenchmarkConcatStingByBytesBuffer(b *testing.B) {
    elems := []string{"1", "2", "3", "4", "5"}
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        var buf bytes.Buffer
        for _, elem := range elems {
            buf.WriteString(elem)
        }
    }
    b.StopTimer()
}

BDD

BDD(Behavior Driven Development),直译是行为驱动开发,主要是为了解决验收功能的业务人员与开发人员之间的沟通问题

package BDD

import (
    . "github.com/smartystreets/goconvey/convey"
    "testing"
)

func TestSpec(t *testing.T) {

    // Only pass t into top-level Convey calls
    Convey("Given some integer with a starting value", t, func() {
        x := 1

        Convey("When the integer is incremented", func() {
            x++

            Convey("The value should be greater by one", func() {
                So(x, ShouldEqual, 2)
            })
        })
    })
}

详细使用点这里

猜你喜欢

转载自www.cnblogs.com/wuyongqiang/p/12146031.html