这是我为从 mongodb 检索文档而编写的处理程序。如果找到文档,我们将相应地加载和呈现模板。如果失败,它将重定向到 404。func EventNextHandler(w http.ResponseWriter, r *http.Request) { search := bson.M{"data.start_time": bson.M{"$gte": time.Now()}} sort := "data.start_time" var result *Event err := db.Find(&Event{}, search).Sort(sort).One(&result) if err != nil && err != mgo.ErrNotFound { panic(err) } if err == mgo.ErrNotFound { fmt.Println("No such object in db. Redirect") http.Redirect(w, r, "/404/", http.StatusFound) return } // TODO: // This is the absolute path parsing of template files so tests will pass // Code can be better organized var eventnext = template.Must(template.ParseFiles( path.Join(conf.Config.ProjectRoot, "templates/_base.html"), path.Join(conf.Config.ProjectRoot, "templates/event_next.html"), )) type templateData struct { Context *conf.Context E *Event } data := templateData{conf.DefaultContext(conf.Config), result} eventnext.Execute(w, data)}手动尝试一下,一切都很好。但是,我似乎无法通过我的单元测试。在相应的测试文件中,这是我的测试代码,用于尝试加载我的EventNextHandler.func TestEventNextHandler(t *testing.T) { // integration test on http requests to EventNextHandler request, _ := http.NewRequest("GET", "/events/next/", nil) response := httptest.NewRecorder() EventNextHandler(response, request) if response.Code != http.StatusOK { t.Fatalf("Non-expected status code%v:\n\tbody: %v", "200", response.Code) }}测试在声明 的行处失败EventNextHandler(response, request)。在我的错误消息中,它指的err := db.Find(&Event{}, search).Sort(sort).One(&result)是我的处理程序代码中的行。在此处完成错误消息:-=== RUN TestEventNextHandler--- FAIL: TestEventNextHandler (0.00 seconds)panic: runtime error: invalid memory address or nil pointer dereference [recovered] panic: runtime error: invalid memory address or nil pointer dereference[signal 0xb code=0x1 addr=0x8 pc=0x113eb8]编写测试的正确方法是什么?考虑到没有从 mongodb 中检索到任何内容的情况,并应用断言来验证这一点,从而编写经过验证的测试。
1 回答
- 1 回答
- 0 关注
- 181 浏览
添加回答
举报
0/150
提交
取消