title: How to unit test a Cobra CLI command which requires internal mocks?
body: <p>I have defined the following Cobra subcommand that I'd like to test the output for using testify:</p>
  <pre><code>var childCmd = &amp;cobra.Command{
      Args:  cobra.MinimumNArgs(1),
      RunE: func(cmd *cobra.Command, args []string) error {
          id := args[0]
          conn := getConn()
          c := newClient(conn)
  
          out, err := c.getResult(cmd.Context(), id)
          if err != nil {
              return err
          }
  
          fmt.Printf(
              &quot;Name:\t%v %v\nCity:\t%v\n&quot;,
              out.GetFirstName().String(),
              out.GetLastName().String(),
              out.GetCity().String(),
          )
  
          return nil
      },
  }
  
  func init() {
      rootCmd.AddCommand(childCmd)
  }
  </code></pre>
  <p>I can test the actual output with something like this:</p>
  <pre><code>func executeCommand(root *cobra.Command, args ...string) (output string, err error) {
      buf := new(bytes.Buffer)
      root.SetOut(buf)
      root.SetErr(buf)
      root.SetArgs(args)
  
      err = root.Execute()
      if err != nil {
          fmt.Println(err)
      }
  
      return buf.String(), err
  }
  
  func TestGetResult(t *testing.T) {
      rootCmd.AddCommand(childCmd)
      output, _ := executeCommand(rootCmd, &quot;child&quot;, &quot;1&quot;)
      assert.Equal(t, &quot;test&quot;, output)
  }
  </code></pre>
  <p>But what I'm missing is how to mock the gRPC client and the its respective call to <code>getResult</code>.
  Is there a better way to create a new gRPC client than within the <code>RunE</code> func that would help facilitate mocking? As of right now, the unit test attempts to connect to a non-existent gRPC client and fails.</p>