me icon indicating copy to clipboard operation
me copied to clipboard

学习 Go (Part 2: go test)

Open nonocast opened this issue 2 years ago • 0 comments

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 -v查看详细信息

代码覆盖率:

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

nonocast avatar Jul 24 '22 16:07 nonocast