如何使用go test标志正确执行测试和基准测试函数?

huangapple go评论80阅读模式
英文:

How to use go test flag to execute test and bench function correctly?

问题

我从Testing flags中学习了关于go flags的内容,并在我的项目中编写了一些测试文件。

这是我的service文件夹:

  • service
    • family_limit_settings.go
    • family_limit_settings_test.go
    • xxxxxx.go(其他go源文件)
    • xxxxxx_test.go(其他go测试源文件)

我的family_limit_settings_test.go文件内容如下:

func TestSaveSettings(t *testing.T) {
	// todo
}

func TestListByFamilyId(t *testing.T) {
	// todo
}

func TestFamilyLimitVerify(t *testing.T) {
	// todo
}

func BenchmarkFamilyListByFamilyId(b *testing.B) {
	// todo
}

func BenchmarkFamilySaveSettings(b *testing.B) {
	// todo
}

func BenchmarkFamilyLimitVerify(b *testing.B) {
	// todo
}

我的第一个问题

我进入这个service文件夹并运行以下命令:

 go test -v -bench=.

但我发现它运行了其他不是基准测试函数的测试函数。(我知道这是因为其他常规测试函数出现了问题)

我的第二个问题

go test -v -bench=. -run=BenchmarkFamilyListByFamilyId

我想执行名为BenchmarkFamilyListByFamilyId的基准测试函数,但我发现它执行了所有的基准测试函数。

英文:

I learn from the go flags from Testing flags

And I write some test files in my project.

This is my service folder:

  • service
    • family_limit_settings.go
    • family_limit_settings_test.go
    • xxxxxx.go (others go source files)
    • xxxxxx_test.go (others go test source files)

and my family_limit_settings_test.go content is as follows:

func TestSaveSettings(t *testing.T) {
	// todo
}

func TestListByFamilyId(t *testing.T) {
	// todo
}

func TestFamilyLimitVerify(t *testing.T) {
	// todo
}

func BenchmarkFamilyListByFamilyId(b *testing.B) {
	// todo
}

func BenchmarkFamilySaveSettings(b *testing.B) {
	// todo
}

func BenchmarkFamilyLimitVerify(b *testing.B) {
	// todo
}

my first question

I cd this service file and run command follow:

 go test -v -bench=.

But I find it run other test function those are not benchmark function.(I know it because something wrong occurs in other common test function)

my second question

go test -v -bench=. -run=BenchmarkFamilyListByFamilyId

I want to execute the benchmark function with the name BenchmarkFamilyListByFamilyId but I found it execute all the benchmark functions.

答案1

得分: 2

-run参数只匹配测试和示例,-bench参数只匹配基准测试。而.是一个正则表达式,匹配所有名称,所以-bench=.会执行所有的基准测试。

要仅执行BenchmarkFamilyListByFamilyId基准测试而不执行任何测试,可以运行类似以下的命令:

go test -v -bench=ByFamilyId -run=XXX
英文:

The -run argument matches tests and examples only, -bench matches benchmarks. And . is a regular expression that matches every name, so -bench=. executes all benchmarks.

To execute only the BenchmarkFamilyListByFamilyId benchmark and none of the tests, run something like

go test -v -bench=ByFamilyId -run=XXX

huangapple
  • 本文由 发表于 2021年9月17日 12:03:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/69217625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定