我想在go lang中模拟memcache缓存数据来避免授权 我尝试使用 gomock 但无法解决,因为我没有任何接口(interface)。

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

尝试使用 gomock 进行模拟

package mock_utils 

gen mock for utils for get access controller (1) 定义一个你想模拟的接口(interface)。

(2) 使用mockgen 从界面生成mock。 (3) 在测试中使用模拟:

请您参考如下方法:

您需要构建您的代码,以便每次此类服务访问都通过接口(interface)实现进行。在您的情况下,理想情况下您应该创建一个界面,如

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

您的 MemcacheStruct 应该实现此接口(interface),并且所有与内存缓存相关的调用都应该从那里发生。就像您的情况一样,GetAccessToken 应该调用 cacheInterface.get(key),其中您的 cacheInterface 应该引用此接口(interface)的内存缓存实现。这是设计您的 go 程序的更好方法,这不仅可以帮助您编写测试,而且在假设您想使用不同的内存数据库来帮助缓存的情况下也有帮助。例如,假设将来您想要使用 Redis 作为您的缓存存储,那么您需要更改的就是创建该接口(interface)的新实现。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!