drhg24275
drhg24275
2016-07-12 05:50

如何使用Go for Unit Testing指定App Engine模板的路径?

  • unit-testing
  • templates

I'm using the built-in template package with Go on App Engine.

I have a handler that renders a template to the output.

templates := []string{"templates/head.html", "templates/footer.html"}

func pageIndex(w http.ResponseWriter, r *http.Request) {
  tpls := append([]string{"templates/index.html"}, templates...)
  tpl := template.Must(template.ParseFiles(tpls...))
  err := tpl.ExecuteTemplate(w, "index", map[string]string{
    "Title": "Index Page",
  })

  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
  }
}

When I run the local development server this works fine.

When I run the unit test to test the page, it panics and gives me the message:

panic: open templates/index.html: no such file or directory [recovered]

The unit test is as follows:

func TestPageIndex(t *testing.T) {
  inst, _ := aetest.NewInstance(nil)
  //ignoring the errors for brevity
  defer inst.Close()

  req, _ := inst.NewRequest("GET", "/", nil)
  resp := httptest.NewRecorder()
  pageIndex(resp, req)
}

Basically, the problem is that for the unit test, the server is unable to find the path of the template.

How do I specify the path for the template files when running the test?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答