<p>Example函数是Go语言中用于文档示例并可执行测试的特殊函数。它定义在_test.go文件中,函数名以Example开头,如func ExampleHello(),通过// Output:注释声明预期输出,从而在go test时自动验证正确性。例如: </p><pre>func ExampleHello() {fmt.Println("hello") // Output: hello}</pre><p>该函数既被godoc提取展示,又在测试中运行。只要实际输出与// Output:后的内容匹配,测试即通过。多行输出需逐行写出: </p><pre>// Output:// Line 1// Line 2</pre><p>可通过命名区分多个用例,如ExampleFibonacci_basic和ExampleFibonacci_edgeCase,分别演示不同场景。支持导入标准库(如bytes)编写协作示例: </p><pre>func ExampleWriteToBuffer() {var buf bytes.Buffer buf.WriteString("test") fmt.Println(buf.String()) // Output: test}</pre><p>若无需测试执行,可省略// Output:,仅作文档说明,如展示HTTP服务器启动: </p><pre>func ExampleStartServer() {// srv := &http.Server{Addr: ":8080"} // log.Fatal(srv.ListenAndServe()) // This example is</code></pre>

在Golang中,example函数是一种特殊的测试形式,它既可以作为文档示例展示代码用法,又能在运行go test时自动执行验证正确性。合理使用example函数能显著提升代码可读性和可维护性。
Go语言通过example_test.go文件中的函数名以Example开头的函数来定义示例。这些函数会被godoc工具提取并显示在文档中,同时也会在测试时被go test执行。
一个基本的example函数结构如下:
func ExampleHello() {
fmt.Println("hello")
// Output: hello
}
注意:必须包含注释// Output:来声明期望输出,否则不会被执行验证。
立即学习“go语言免费学习笔记(深入)”;
example函数最常见用途是演示API调用方式,并验证其输出是否符合预期。
func ExampleGreet() {
greeting := greet("Alice")
fmt.Println(greeting)
// Output: Hello, Alice!
}
只要函数末尾有// Output:且内容匹配实际输出,测试就会通过。如果输出多行,需完整写出:
// Output: // Line 1 // Line 2
可以通过命名区分不同用例,比如:
ExampleFibonacci_basicExampleFibonacci_edgeCase
func ExampleFibonacci_basic() {
fmt.Println(Fibonacci(5))
// Output: 5
}
func ExampleFibonacci_edgeCase() {
fmt.Println(Fibonacci(0))
// Output: 0
}
</font>
当需要引入其他包(如io、bytes)时,仍可正常编写example函数:
func ExampleWriteToBuffer() {
var buf bytes.Buffer
buf.WriteString("test")
fmt.Println(buf.String())
// Output: test
}
这类示例有助于展示如何组合标准库使用你的接口。
有时你只想展示用法而不验证输出,可以省略// Output:,但这样就不会参与测试执行:
func ExampleStartServer() {
// srv := &http.Server{Addr: ":8080"}
// log.Fatal(srv.ListenAndServe())
// This example is not executed.
}
这种写法适合复杂启动流程或无法自动化验证的场景。
基本上就这些。合理使用example函数能让API更易懂,也能增强测试覆盖。关键点是记住要加// Output:才能触发执行验证,函数命名要规范,文件放在*_test.go中。不复杂但容易忽略细节。
以上就是如何在Golang中使用example函数进行示例测试_Golang example函数示例测试方法汇总的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号