我试图在单元测试中模拟 cmd.Start() 并且无法弄清楚
我们需要模拟整个函数还是可以模拟 cmd.Start() 函数?
有人可以帮助我吗?
package main
import (
"bytes"
"fmt"
"os/exec"
)
var execCommand = exec.Command
func main() {
stdout := &bytes.Buffer{}
cmd := execCommand("cmd")
syscall.SysProcAttr := &syscall.SysProcAttr{CmdLine: "/S /c C:\\Temp\\test.exe /S C:\\Temp\\test.log"}
cmd.Stdout = stdout
errs := cmd.Start()
if errs != nil {
fmt.Println("command run fialed :", errs)
fmt.Println("OUTPUT :", stdout.String())
}
}
单元测试:
func fakeExecCommand(command string, args ...string) *exec.Cmd {
cs := []string{"-test.run=TestExecCommandHelper", "--", command}
cs = append(cs, args...)
cmd := exec.Command(os.Args[0], cs...)
es := strconv.Itoa(mockedExitStatus)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1", "STDOUT=" + mockedStdout, "EXIT_STATUS=" + es}
return cmd
}
倚天杖
相关分类