天天看点

golang subprocess testsgolang Subprocess tests

golang Subprocess tests

Sometimes you need to test the behavior of a process, not just a function.

func Crasher() {
    fmt.Println("Going down in flames!")
    os.Exit(1)
}           

To test this code, we invoke the test binary itself as a subprocess:

func TestCrasher(t *testing.T) {
    if os.Getenv("BE_CRASHER") == "1" {
        Crasher()
        return
    }
    cmd := exec.Command(os.Args[0], "-test.run=TestCrasher")
    cmd.Env = append(os.Environ(), "BE_CRASHER=1")
    err := cmd.Run()
    if e, ok := err.(*exec.ExitError); ok && !e.Success() {
        return
    }
    t.Fatalf("process ran with err %v, want exit status 1", err)
}           

核心技巧在于os.args[0]可以获取到真实的可执行 test 程序,从而改变环境变量.