Reputation: 101
I use cobra and viper for context. I want to test a subcommand with flag. So I have a root command with init function as following
SubCmd.Flags().Bool("test-flag", false, "It is a flag")
RootCmd.AddCommand(SubCmd)
Now I test the command as follows
func TestSubCommand(t *testing.T) {
var bufError bytes.Buffer
RootCmd.SetOut(&buf)
RootCmd.SetErr(&bufError)
RootCmd.SetArgs([]string{"subcmd", "--test-flag"})
err := RootCmd.Execute()
assert.NoError(t, err)
}
However in my subcommand
cmd.Flags().GetBool("test-flag")
is always false. So, I am not able to test the flag functionality.
Any solutions on how to test the flag functionalities? Any workarounds or corrections?
Upvotes: 2
Views: 34