go - 如何在 golang 中模拟 memcached 进行单元测试?

标签 go memcached gomock

我想在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)的新实现。

关于go - 如何在 golang 中模拟 memcached 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49688682/

相关文章:

go - 从 goroutine 中的缓冲 channel 读取时的执行顺序

go - 如何使用未导出结构体的函数

go - 从 golang 中的响应流创建 Imagemagick 对象

go - 如何使用 reflect.TypeOf([]string {"a"}).Elem()?

unit-testing - 如何比较/匹配模拟中的闭包?

python - Django 原子增加初始值

PHP、Memcached 从命令行运行,但不能从 Web 运行

python - memcached 可以有效处理多大的数据?

unit-testing - 使用 Gomock 测试返回错误 : Expected call has already been called the max number of times

Golang : how to mock . ..interface{} arguents 使用 gomock