2 回答

TA貢獻1799條經驗 獲得超8個贊
#1
嘗試運行TestMain()
就像嘗試運行main()
。你不這樣做,操作系統為你做這件事。
TestMain是在 Go 1.4 中引入的,用于幫助設置/拆卸測試環境,它被調用而不是運行測試;引用發行說明:
如果測試代碼包含函數
func?TestMain(m?*testing.M)該函數將被調用而不是直接運行測試。M 結構包含訪問和運行測試的方法。
#2
用于ioutil.TempDir()
創建臨時目錄。
tmpDir, err := ioutil.TempDir("", "test_output")
if err != nil {
? ? // handle err
}
它將負責創建目錄。您稍后應該使用os.Remove(tmpDir)刪除臨時目錄。
您可以將它與Tim Peoples的建議稍微修改后的版本一起使用,例如:
func TestCompile(t *testing.T) {
? ? tmpDir, err := ioutil.TempDir("", "testdata")
? ? if err != nil {
? ? ? ? t.Error(err)
? ? }
? ? defer os.Remove(tmpDir)
? ? tests := []struct {
? ? ? ? name, inFile, outFile string
? ? ? ? err? ? ? ? ? ? ? ? ? ?error
? ? }{
? ? ? ? {"OutputFileCreated", "correct.c", "correct_out", nil},
? ? ? ? {"OutputFileNotCreatedForIncorrectSource", "wrong.c", "wrong_out", someErr},
? ? }
? ? for _, test := range tests {
? ? ? ? var (
? ? ? ? ? ? in? = filepath.Join("testdata", test.inFile)
? ? ? ? ? ? out = filepath.Join(tmpDir, test.outFile)
? ? ? ? )
? ? ? ? t.Run(test.name, func(t *testing.T) {
? ? ? ? ? ? err = Compile(in, out)
? ? ? ? ? ? if err != test.err {
? ? ? ? ? ? ? ? t.Errorf("Compile(%q, %q) == %v; Wanted %v", in, out, err, test.err)
? ? ? ? ? ? }
? ? ? ? })
? ? }
}

TA貢獻1836條經驗 獲得超3個贊
很可能,您的問題與您傳遞給的模式os.Mkdir(...)值有關。您提供的是666十進制,它是01232八進制的(或者,如果您愿意,權限字符串為d-w--wx-wT),我認為這并不是您真正想要的。
而不是666,您應該指定0666-- 前導 0 表示您的值是八進制表示法。
另外,您的兩個測試實際上是相同的;與其使用 aTestMain(...)來執行設置,我建議使用*T.Run(...)從單個頂級Test*函數執行測試。是這樣的:
gcc_test.go:
package gcc
import (
"testing"
"path/filepath"
"os"
)
const testoutput = "testoutput"
type testcase struct {
inFile string
outFile string
err error
}
func (tc *testcase) test(t *testing.T) {
var (
in = filepath.Join("testdata", tc.inFile)
out = filepath.Join(testoutput, tc.outFile)
)
if err := Compile(in, out); err != tc.err {
t.Errorf("Compile(%q, %q) == %v; Wanted %v", in, out, err, tc.err)
}
}
func TestCompile(t *testing.T) {
os.Mkdir(testoutput, 0666)
tests := map[string]*testcase{
"correct": &testcase{"correct.c", "correct_out", nil},
"wrong": &testcase{"wrong.c", "wrong_out", expectedError},
}
for name, tc := range tests {
t.Run(name, tc.test)
}
}
- 2 回答
- 0 關注
- 183 瀏覽
添加回答
舉報