Home > Blockchain >  Go test fails db query (nil pointer) but works with Postman/Curl
Go test fails db query (nil pointer) but works with Postman/Curl

Time:11-26

I'm testing GetCats() which is a function that gets all 'cats' from a mysql database. When I hit the endpoint through postman, there are no nil pointer errors due to 'COALESCE' which sets the field to an empty string if null.

However, when I test the function, there is a nil pointer error and the program panics out.

  • 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")

    //------------------------------------------------//

Any help would be greatly appreciated!

extra notes:

  • 'name' is not null in database, no need for coalesce on that field
  • there are a few null fields in the database (intentional)
  • just confused as to how the query works in postman but not while calling internally from _test.go

CodePudding user response:

Probably the Db object is not initialized properly in the test. You'd better define a struct and inject DB as dependency and use a fake DB object in your test. For example,

// 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)
        }
}

  • Related