dongwaner1367 2018-04-06 08:36
浏览 39

如何在Go lang中模拟内存缓存进行单元测试?

I want to mock memcache cache data in go lang to avoid authhorization i tried with gomock but couldn't work out as i dont have any interface for it.

func getAccessTokenFromCache(accessToken string)

func TestSendData(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockObj := mock_utils.NewMockCacheInterface(mockCtrl)
mockObj.EXPECT().GetAccessToken("abcd") 
var jsonStr = []byte(`{
    "devices": [
        {"id": "avccc",

        "data":"abcd/"
        }
            ]
}`)
req, err := http.NewRequest("POST", "/send/v1/data", 
bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
 req.Header.Set("Authorization", "d958372f5039e28")

rr := httptest.NewRecorder()
handler := http.HandlerFunc(SendData)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != 200 {
    t.Errorf("handler returned wrong status code: got %v want %v",
        status, http.StatusOK)
}
expected := `{"error":"Invalid access token"}`
body, _ := ioutil.ReadAll(rr.Body)

if string(body) != expected {
    t.Errorf("handler returned unexpected body: got %v want %v",
        string(body), expected)
}




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

accessToken := r.Header.Get(constants.AUTHORIZATION_HEADER_KEY)

t := utils.CacheType{At1: accessToken}
a := utils.CacheInterface(t)
isAccessTokenValid := utils.CacheInterface.GetAccessToken(a, accessToken)

if !isAccessTokenValid {
    RespondError(w, http.StatusUnauthorized, "Invalid access token")
    return
}
response := make(map[string]string, 1)
response["message"] = "success"
RespondJSON(w, http.StatusOK, response)

}

tried to mock using gomock

package mock_utils

gen mock for utils for get access controler (1) Define an interface that you wish to mock.

(2) Use mockgen to generate a mock from the interface. (3) Use the mock in a test:

  • 写回答

1条回答 默认 最新

  • duanlipeng4136 2018-04-06 08:53
    关注

    You need to architect your code such that every such access to a service happens via an interface implementation. In your case, you should ideally create an interface like

    type CacheInterface interface {
          Set(key string, val interface{}) error
          Get(key string) (interface{},error)
    }
    

    Your MemcacheStruct should implement this interface and all your memcache related calls should happen from there. Like in your case GetAccessToken should call cacheInterface.get(key) wherein your cacheInterface should refer to memcache implementation of this interface. This is a way better way to design your go programs and this would not only help you in writing tests but would also help in case let's say you want to use a different in memory database to help with caching. Like for ex., let's say in future if you want to use redis as your cache storage, then all you need to change is create a new implementation of this interface.

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大