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{"-test.run=TestHelperCommand", "--", executable}
    newArgs = append(newArgs, args...)

    cmd := exec.Command(os.Args[0], newArgs...)
    cmd.Env = []string{
"USE_HELPER_COMMAND=1",
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" {
        return
    }

    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"))
    os.Exit(exitCode)
}在此输入代码...

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/a2849d6b-852b-4d8d-9f10-269722a4b514%40googlegroups.com.

Reply via email to