Currently I am using the following code to mock the exec.Command. But there 
are two issues:
1. I expect the code being tested gets the expected output message (value 
of the variable 'msg') from STDOUT, but actually what it gets from STDOUT 
is always "PASS", which should be the output of the golang unit test result.
2. When the exit code of "TestHelperCommand" is non-zero, then I expect the 
function which calls fakeExecCommand should get an error response, but it 
doesn't. What do I miss?

// fakeExecCommand is used to replace the real command in unit test
func fakeExecCommand(executable string, args ...string) *exec.Cmd {
    newArgs := []string{"", "--", executable}
    newArgs = append(newArgs, args...)

    cmd := exec.Command(os.Args[0], newArgs...)
    cmd.Env = []string{
fmt.Sprintf("STDOUT=%s", msg),
fmt.Sprintf("EXIT_STATUS=%d", exitCode),

    return cmd

func TestHelperCommand(t *testing.T) {
    if os.Getenv("USE_HELPER_COMMAND") != "1" {

    stdOutMsg := os.Getenv("STDOUT")
    if len(stdOutMsg) > 0 {
        fmt.Fprintf(os.Stdout, stdOutMsg)

    stdErrMsg := os.Getenv("STDERR")
    if len(stdErrMsg) > 0 {
        fmt.Fprintf(os.Stderr, stdErrMsg)

    exitCode, _ := strconv.Atoi(os.Getenv("EXIT_STATUS"))

You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
To view this discussion on the web visit

Reply via email to