3 回答

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
我發(fā)現(xiàn)對(duì)于此類(lèi)測(cè)試非常簡(jiǎn)單的另一種方法是將測(cè)試資產(chǎn)放置在相對(duì)于包的 test_data 目錄中。在我的測(cè)試文件中,我通常會(huì)創(chuàng)建一個(gè)幫助程序來(lái)創(chuàng)建 *http.Request 的實(shí)例,它允許我在 multipart.File 上非常輕松地運(yùn)行表測(cè)試(為簡(jiǎn)潔起見(jiàn),已刪除錯(cuò)誤檢查)。
func createMockRequest(pathToFile string) *http.Request {
file, err := os.Open(pathToFile)
if err != nil {
return nil
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filepath.Base(pathToFile))
if err != nil {
return nil
}
_, _ = io.Copy(part, file)
err = writer.Close()
if err != nil {
return nil
}
// the body is the only important data for creating a new request with the form data attached
req, _ := http.NewRequest("POST", "", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req
}
- 3 回答
- 0 關(guān)注
- 453 瀏覽
添加回答
舉報(bào)