我正在測驗 GetCats(),它是一個從 mysql 資料庫中獲取所有“貓”的函式。當我通過郵遞員到達端點時,由于“COALESCE”將欄位設定為空字串(如果為空),因此不會出現空指標錯誤。
但是,當我測驗該函式時,出現了一個 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 內部呼叫時卻沒有
uj5u.com熱心網友回復:
可能 Db 物件在測驗中沒有正確初始化。您最好定義一個結構并將 DB 作為依賴項注入,并在測驗中使用假 DB 物件。例如,
// handlers.go
import (
"database/sql"
"net/http"
)
type App struct {
DB *sql.DB
}
func (a *App) GetCats(w http.ResponseWriter, r *http.Request) {
// var animals []Animal
res, err := a.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")
// ....
}
// handlers_test.go
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
func TestGetCats(t *testing.T) {
db, _, err := sqlmock.New()
if err != nil {
t.Fatalf("an error %s was not expected when openning a stub database connection", err)
}
app := &App{
DB: db,
}
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()
// DB expected actions...
handler := http.HandlerFunc(app.GetCats)
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusOK {
t.Errorf("getCats return wrong status code: got %v but want %v", recorder.Code, http.StatusOK)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365853.html
上一篇:復合觸發器僅觸發一次
