N
N
NubasLol2019-06-03 13:39:28
go
NubasLol, 2019-06-03 13:39:28

Golang how to test handlers that return a template?

func (c Controller) Index(w http.ResponseWriter, r *http.Request) {

  tmpl, _ := template.ParseFiles("")

  _ = tmpl.Execute(w, templateData)
}


req, _ := http.NewRequest("GET", "/sites", nil)

rr := httptest.NewRecorder()
handler := http.HandlerFunc(controller.Index)

handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusOK, rr.Code)

Throws an error where tmpl.Execute(w, templateData)

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x595bfe]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2019-06-03
@NubasLol

tmpl, _ := template.ParseFiles("")
You do not check the returned error here and it is quite logical to panic later.
PS You shouldn't parse the template every time the handler is called. It must be parsed once at the start of the application.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question