Following the example at https://golang.org/pkg/os/exec/#Cmd.StdoutPipe, suppose I have a function getPerson() defined like so:
package stdoutexample
import (
"encoding/json"
"os/exec"
)
// Person represents a person
type Person struct {
Name string
Age int
}
func getPerson() (Person, error) {
person := Person{}
cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`)
stdout, err := cmd.StdoutPipe()
if err != nil {
return person, err
}
if err := cmd.Start(); err != nil {
return person, err
}
if err := json.NewDecoder(stdout).Decode(&person); err != nil {
return person, err
}
if err := cmd.Wait(); err != nil {
return person, err
}
return person, nil
}
In my 'real' application, the command run can have different outputs, I'd like to write test cases for each of these scenarios. However, I'm not sure how to go about this.
So far all I have is a test case for one case:
package stdoutexample
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetPerson(t *testing.T) {
person, err := getPerson()
require.NoError(t, err)
assert.Equal(t, person.Name, "Bob")
assert.Equal(t, person.Age, 32)
}
Perhaps the way to go about this is to split this function into two parts, one which writes the output of the command to a string, and another which decodes the output of a string?