温温酱
我找到了一种使用多级子命令测试命令的简单方法,它不专业但效果很好。假设我们有这样的命令RootCmd = &cobra.Command{ Use: "cliName", Short: "Desc", }SubCmd = &cobra.Command{ Use: "subName", Short: "Desc", }subOfSubCmd = &cobra.Command{ Use: "subOfSub", Short: "Desc", Run: Exec }//commands relationshipRootCmd.AddCommand(SubCmd)SubCmd.AddCommand(subOfSubCmd)在测试 subOfSubCmd 时,我们可以这样做:func TestCmd(t *testing.T) {convey.Convey("test cmd", t, func() { args := []string{"subName", "subOfSub"} RootCmd.SetArgs(args) RootCmd.Execute() })}