Cobra + Viper Golang How to test subcommands?

Viewed 9662

I am developing an web app with Go. So far so good, but now I am integrating Wercker as a CI tool and started caring about testing. But my app relies heavily on Cobra/Viper configuration/flags/environment_variables scheme, and I do not know how to properly init Viper values before running my test suite. Any help would be much appreciated.

2 Answers

i have found an easy way to test commands with multiple level sub commands, it is not professional but it worked well.

assume we have a command like this

RootCmd = &cobra.Command{
            Use:   "cliName",
            Short: "Desc",
    }

SubCmd = &cobra.Command{
            Use:   "subName",
            Short: "Desc",
    }

subOfSubCmd = &cobra.Command{
            Use:   "subOfSub",
            Short: "Desc",
            Run: Exec
    }

//commands relationship
RootCmd.AddCommand(SubCmd)
SubCmd.AddCommand(subOfSubCmd)

When testing the subOfSubCmd we can do this way:

func TestCmd(t *testing.T) {
convey.Convey("test cmd", t, func() {
    args := []string{"subName", "subOfSub"}
    RootCmd.SetArgs(args)
    RootCmd.Execute()
    })
}
Related