douou9094747 2018-02-12 12:29
浏览 39
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • dongwu8653 2018-02-13 10:39
    关注

    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)
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器