Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
nonocast opened this issue Jul 24, 2022 · 0 comments
Open

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

nonocast opened this issue Jul 24, 2022 · 0 comments

Comments

@nonocast
Copy link
Owner

nonocast commented Jul 24, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant