rob*_*y22 3 unit-testing mocking go gomock
注意:不是使用 testify - 不同的库两次使用不同的输入和输出来重复模拟接口方法。
我正在使用该github.com/golang/mock/gomock
库来模拟 HTTP 客户端接口,以测试代码的行为。Post()
我的代码在客户端上使用相同的方法两次,但针对两个不同的端点。
我试过:
mockUc.EXPECT().
Post("m-elasticsearch/_sql/translate", gomock.Eq(expectedQuery), gomock.Any(), gomock.Any()).
SetArg(2, esQuery).
Return(http.StatusOK, nil).
Times(1)
mockUc.EXPECT().
Post("m-elasticsearch/app-*/_search", gomock.Eq(esQuery), gomock.Any(), gomock.Any()).
SetArg(2, logResults).
Return(http.StatusOK, nil).
Times(1)
Run Code Online (Sandbox Code Playgroud)
但这给了我错误,告诉我EXPECT()
在第一次调用时正在考虑第二个:
expected call at [...] doesn't match the argument at index 0.
Got: m-elasticsearch/_sql/translate (string)
Want: is equal to m-elasticsearch/app-*/_search (string)
Run Code Online (Sandbox Code Playgroud)
然后我尝试gomock.InOrder()
像这样使用:
expected call at [...] doesn't match the argument at index 0.
Got: m-elasticsearch/_sql/translate (string)
Want: is equal to m-elasticsearch/app-*/_search (string)
Run Code Online (Sandbox Code Playgroud)
但这也没有帮助。
我在这里尝试做的事情可能吗?
小智 5
您可以使用 DoAndReturn 方法并在一个 EXPECT 中返回所需的值,而不是编写两个 EXPECT。我无法编写类型,因为我不知道方法签名。
mockUc.
EXPECT().
Post(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
DoAndReturn(func(url, query string, ...) (int, error) {
if url == "m-elasticsearch/_sql/translate" {
return http.StatusOK, nil
} else {
return http.StatusOK, nil
}
})
Run Code Online (Sandbox Code Playgroud)