Testing upload file

Hi all
Tell me please how correct write test for my simple handler to upload file

func UploadFile(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(1024)
	file, _, err := r.FormFile("uploadFile")
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		io.WriteString(w, "Invalid file to upload")
		return
	}
	defer file.Close()

	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		io.WriteString(w, "Read file error - Invalid data in file")
		return
	}
}

I want get test file from tmp folder inside package and send request in my test with this file
Thanks!

What have you written so far? I don’t think you are asking the right way: first you tell us what you tried, then we tell you what to try next. We are not here to write code for you.

One thing you can do, for example, is to implement your own (mock) http.ResponseWriter that tests that you get the right data. This way you don’t need to write to disk, which is not something unit tests should do (usually).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.