<分区>
我在开发一个小型 CLI 应用程序。我正在尝试编写单元测试。我有一个函数可以使用 fmt.Println
/fmt.Printf
将一些输出作为表格呈现给命令行。我想知道如何在单元测试中捕获该输出以确保我得到预期的结果?下面只是一个准系统框架,在某种程度上代表了我正在努力实现的目标。
main.go
package main
import (
"fmt"
"io"
)
func print() {
fmt.Println("Hello world")
}
func main() {
print()
}
main_test.go
package main
import "testing"
func TestPrint(t *testing.T) {
expected := "Hello world"
print() // somehow capture the output
// if got != expected {
// t.Errorf("Does not match")
// }
}
我尝试了一些方法,例如 How to check a log/output in go test?但运气极差,但这可能是由于我的误解。