【发布时间】:2019-10-22 21:15:25
【问题描述】:
我在开发一个小型 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?,但运气不佳,但这可能是由于我的误解。
【问题讨论】:
-
接口是你测试的好朋友。
-
@Volker:一般来说是好的建议,但并非总是可行。
标签: unit-testing go testing