问题描述
我正在尝试测试我用 Cobra 编写的 CLI 应用程序,特别是测试子命令是否正确写入 STDOUT。为此,我尝试将输出从 STDOUT 重定向到我的缓冲区。不幸的是,无论出于何种原因,对于通过调用 Commands() 获得的子命令,Setout() 函数都没有按预期运行。
这是我的代码:
package cmd
import (
"os"
"testing"
"bytes"
"io/IoUtil"
"github.com/spf13/cobra"
)
func NewCmd() *cobra.Command {
cmd := &cobra.Command{}
cmd.AddCommand(NewChildCmd())
return cmd
}
func NewChildCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "child",Run: func(cmd *cobra.Command,args []string) {
os.Stdout.WriteString("TEST\n")
},}
return cmd
}
func TestChild(t *testing.T) {
cmd := NewCmd()
buffer := new(bytes.Buffer)
subCommands := cmd.Commands()
for i := range subCommands {
subCommands[i].Setout(buffer)
}
cmd.Setout(buffer)
cmd.SetArgs([]string{"child"})
cmd.Execute()
out,err := IoUtil.ReadAll(buffer)
if err != nil {
t.Fatal(err)
}
if string(out) != "child" {
t.Fatalf("Expected \"TEST\",got \"%s\"",string(out))
}
}
这是测试输出:
TEST
--- FAIL: TestChild (0.00s)
cmd/my_test.go:44: Expected "TEST",got ""
FAIL
FAIL cmd 0.004s
FAIL
解决方法
显然,SetOut() 无法更改直接发送到 os.Stdout 的输出,而是必须使用 cmd.Println(),然后一切都按预期进行。