【发布时间】:2022-01-03 09:42:17
【问题描述】:
我正在测试 GetCats(),这是一个从 mysql 数据库中获取所有“猫”的函数。当我通过邮递员到达端点时,由于 'COALESCE' 将字段设置为空字符串(如果为 null),因此不会出现 nil 指针错误。
但是,当我测试该函数时,出现了一个 nil 指针错误并且程序崩溃了。
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
_test.go
func TestGetCats(t *testing.T) {
// create new request to /cats endpoint, nil => body io.Reader
req, err := http.NewRequest("GET", "/cats", nil)
if err != nil {
t.Fatal(err)
}
// Will store response received from /cats endpoint => pointer to ResonseRecorder struct
recorder := httptest.NewRecorder()
handler := http.HandlerFunc(handlers.GetCats)
// ----(FAILS HERE) hit endpoint with recorder and request (FAILS HERE) ----//
handler.ServeHTTP(recorder, req)
// ------------------------------------------------------------------------//
// test recorder status code
if recorder.Code != http.StatusOK {
t.Errorf("getCats return wrong status code: got %v but want %v", recorder.Code, http.StatusOK)
}
cathandlers.go
func GetCats(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var animals []Animal
// ---------------Program panics on this query --------------------//
// cannot input null values into struct => return empty string instead
res, err := Db.Query("SELECT id, name,
COALESCE(age, '') as age,
COALESCE(color, '') as color,
COALESCE(gender, '') as gender,
COALESCE(breed, '') as breed,
COALESCE(weight, '') as weight FROM cats")
//------------------------------------------------//
任何帮助将不胜感激!
补充说明:
- 'name' 在数据库中不为空,不需要在该字段上合并
- 数据库中有几个空字段(故意)
- 只是对查询在邮递员中的工作方式感到困惑,但在从 _test.go 内部调用时却没有
【问题讨论】:
-
我的猜测是,这与查询本身没有太大关系,而是与
Db的初始化方式有关。也许它是由您的main()函数初始化的,在运行测试时不会执行。 -
谢谢@mkopriva,这正是问题所在
标签: mysql rest go testing null