nonocast / me

记录和分享技术的博客
http://nonocast.cn
MIT License
20 stars 0 forks source link

学习 Go (Part 2: go test) #315

Open nonocast opened 2 years ago

nonocast commented 2 years ago

Go内置了单元测试'go test',这个真的好,而且推荐的方式foo.go对应test_foo.go,同目录。

app.go

package main

import "fmt"

func Add(x int, y int) int {
    return x + y
}

func main() {
    fmt.Printf("1+2=%d\n", Add(1, 2))
}

app_test.go (以_test结尾)

package main

import "testing"

func TestAdd(t *testing.T) {
    got := Add(1, 2)
    expected := 3

    if expected != got {
        t.Errorf("got %d, expected %d", got, expected)
    }
}

运行单元测试:

~ go test
PASS
ok      nonocast.cn/hello       1.497s

代码覆盖率:

go test -cover
PASS
coverage: 50.0% of statements
ok      nonocast.cn/hello       0.585s

然后可以输出成profile,然后通过browser查看:

~ go test -coverprofile=coverage.out
PASS
coverage: 50.0% of statements
ok      nonocast.cn/hello       0.244s
~ go tool cover -html=coverage.out