用于处理程序单元测试的模拟功能

I am stuck over testing with mocking, Here is my route for handler:

r.Handle("/users/{userID}", negroni.New(
        negroni.HandlerFunc(validateTokenMiddleware),
        negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            getUserDetailsHandler(w, r, db)
        })),
    )).Methods("GET")

And here is my handler:

func getUserDetailsHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) {

    w.Header().Set("Content-Type", "application/json; charset=UTF-8")

    //Create UserDetailsView instance
    var userview UserDetailsView

    //Get varibale from mux
    vars := mux.Vars(r)

    //UserID  fetches userId from vars
    userID := vars["userID"]

    //Get user Information by wpUsersID
    wuis := store.NewWpUserInformationStore(db)
    userInformation, _:= wuis.GetByID(uID)


        json.NewEncoder(w).Encode(userview); 

        //Print result
        w.WriteHeader(http.StatusOK)
}

And i mock the function which is in store package named as GetByID which is looks like this :

type wpUserInfoMockStore struct {
    mock.Mock
}

func (m *wpUserInfoMockStore) GetByID(user *WpUserInformation) error {
    rets := m.Called(user)
    return rets.Error(0)
}

//InitMockStore store
func InitMockStore() *wpUserInfoMockStore {
    s := new(wpUserInfoMockStore)
    //store = s
    return s
}

And i write test case for handler but i got an error cannot convert getUserDetailsHandler (type func(http.ResponseWriter, *http.Request, *sql.DB)) to type http.HandlerFunc but i can not find why is it happened, here i'm using reference for this https://github.com/sohamkamani/blog_example__go_web_db and here is my test case code:

func TestGetUserDetailsTes(t *testing.T) {

    // Initialize the mock store
    mockStore := store.InitMockStore()

    mockStore.On("GetByID").Return([]*store.WpUserInformation{{
        21,
        sql.NullString{String: "john"},
        sql.NullString{String: "Sorensen"},
        0}}, nil).Once()

    req, err := http.NewRequest("GET", "", nil)

    //if requests gives error
    if err != nil {
        panic(err.Error())
    }

    //parameters for generateTestUserJWT are set
    testUser.ID = "22"
    testUser.UserName = "johns"
    testUser.Depot = "NYC"

    //JWT generated
    refToken, err := generateTestJWT(testUser, false)

    //handling error while generating token
    if err != nil {
        panic(err.Error())
    }

    //token returned is concatenated with Bearer string
    newToken = "Bearer " + refToken

    //request authorization header is set
    req.Header.Set("Authorization", newToken)
    req.Header.Set("Latitude", "123.12")
    req.Header.Set("Longitude", "456.45")

    //response is set
    w := httptest.NewRecorder()

    hf := http.HandlerFunc(getUserDetailsHandler)

    hf.ServeHTTP(w, req)

    //if response code is not statusOK then test fails
    if w.Code != http.StatusOK {
        t.Errorf("/users/{userID} GET request failed, got: %d, want: %d.", w.Code, http.StatusOK)
    }
}

As you see i test handler without url like req, err := http.NewRequest("GET", "", nil) but when i used link inside then i can not able to use mock functions, here what am i missing/fault please help me out. Thank you.

Use a middleware handler for generating the function. Pass a handler in your main function which will call your middleware returning http.handler. That way you can pass db object to your main data and which will call the middle ware returning handler.

func getUserDetailsHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) http.HandlerFunc{

    return func(w http.ResponseWriter, r *http.Request) {

        w.Header().Set("Content-Type", "application/json; charset=UTF-8")

        //Create UserDetailsView instance
        var userview UserDetailsView

        //Get varibale from mux
        vars := mux.Vars(r)

        //UserID  fetches userId from vars
        userID := vars["userID"]

        //Get user Information by wpUsersID
        wuis := store.NewWpUserInformationStore(db)
        userInformation, _:= wuis.GetByID(uID)


        json.NewEncoder(w).Encode(userview); 

        //Print result
        w.WriteHeader(http.StatusOK)
   }
}