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

    报告相同问题?

    悬赏问题

    • ¥40 找同学帮敲Python代码
    • ¥15 MYSQL 订单的商品明细重复计算问题
    • ¥15 微信实时共享位置修改
    • ¥100 TG的session协议号转成直登号号后客户端登录几分钟后自动退出设备
    • ¥50 共模反馈回路的小信号增益
    • ¥15 arduino ssd1306函数与tone函数放歌代码不兼容问题
    • ¥70 0.96版本hbase的row_key里含有双引号,无法deleteall
    • ¥15 诊断性META分析合并效能的检验
    • ¥15 请问abb根据色块判断奇偶数并根据批次号放入仓储
    • ¥66 开发PC客户端一定也要开发上位机吗?