社区专栏>golang中关于测试用例的一些心得>
1. golang测试用例的编写
- 测试文件名必须以test_开头,加上被测文件的名称;
- 测试函数名必须以Test开头;
2. 运行测试用例
- 单个文件夹中的测试用例,执行:go test -v -covermode=count -coverprofile=cover.out,go tool cover -html=cover.out -o cover.html;
- 整个项目所有的测试用例,执行:go test -covermode=count -coverprofile=cover.out -run="^Test" -coverpkg=$(go list ./... | grep -v "/test" | tr '\n' ',') ./... ,go tool cover -html=cover.out -o cover.html;
3.注意事项
- 如果运行测试用例的时候,没有指定是否使用内联优化(编译器内联(inlining)是一个关键的优化手段。它通过将小函数体直接嵌入调用处,减少函数调用开销,提升执行效率),默认是使用的;这种情况可能会有某些测试用例的模拟代码没有生效,所以需要禁用;
- go test -v -gcflags "all=-N -l" -covermode=count -coverprofile=cover.out,其中的gcflags "all=-N -l"禁用使用内联优化。
1. golang测试用例的编写
- 测试文件名必须以test_开头,加上被测文件的名称;
- 测试函数名必须以Test开头;
2. 运行测试用例
- 单个文件夹中的测试用例,执行:go test -v -covermode=count -coverprofile=cover.out,go tool cover -html=cover.out -o cover.html;
- 整个项目所有的测试用例,执行:go test -covermode=count -coverprofile=cover.out -run="^Test" -coverpkg=$(go list ./... | grep -v "/test" | tr '\n' ',') ./... ,go tool cover -html=cover.out -o cover.html;
3.注意事项
- 如果运行测试用例的时候,没有指定是否使用内联优化(编译器内联(inlining)是一个关键的优化手段。它通过将小函数体直接嵌入调用处,减少函数调用开销,提升执行效率),默认是使用的;这种情况可能会有某些测试用例的模拟代码没有生效,所以需要禁用;
- go test -v -gcflags "all=-N -l" -covermode=count -coverprofile=cover.out,其中的gcflags "all=-N -l"禁用使用内联优化。