I found the 'go test' PASS, but if I specific sub test, it will fail, here I give a global variable sample, 'go test' will PASS, and 'go test -run f/sample2' will FAIL.
I'm wonder what's the general rules should I follow to prevent such problems?
t.go
package main
import "fmt"
var g string
func f(s string) string {
g = g + s
return s + g
}
func main() {
fmt.Println(f("a"))
}
t_test.go
package main
import (
"testing"
)
func Test_f(t *testing.T) {
tests := []struct {
name string
g string
s string
r string
}{
{"simple", "g1", "s1", "s1s1"},
{"simple2", "g2", "s2", "s2s1s2"},
{"simple3", "g3", "s3", "s3s1s2s3"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
//g = tt.g
r := f(tt.s)
if r != tt.r {
t.Error("r=", r, "expect r=", tt.r)
}
})
}
}
If global variable is the problem, I often write something like osExit fmtPrint to replace os.Exit and fmt.Print on testing, how to overcome these?