首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >输入不同的两次相同方法

输入不同的两次相同方法
EN

Stack Overflow用户
提问于 2022-05-21 00:29:17
回答 1查看 2.6K关注 0票数 1

注意:不是Mock interface method twice with different input and output using testify的副本-不同的库。

为了测试代码的行为,我使用github.com/golang/mock/gomock库来模拟HTTP接口。我的代码两次在客户机上使用相同的Post()方法,但对两个不同的端点使用。

我试过:

代码语言:javascript
复制
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)

但这给了我错误,告诉我在第一个电话中正在考虑第二个EXPECT()

代码语言:javascript
复制
 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)

然后我试着像这样使用gomock.InOrder()

代码语言:javascript
复制
first := mockUc.EXPECT().
    Post("m-elasticsearch/_sql/translate", gomock.Eq(expectedQuery), gomock.Any(), gomock.Any()).
    SetArg(2, esQuery).
    Return(http.StatusOK, nil).
    Times(1)
second := mockUc.EXPECT().
    Post("m-elasticsearch/app-*/_search", gomock.Eq(esQuery), gomock.Any(), gomock.Any()).
    SetArg(2, logResults).
    Return(http.StatusOK, nil).
    Times(1)

gomock.InOrder(first, second)

但这也无济于事。

我在这里做的事有可能吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-21 13:44:57

与编写两个期望值不同,您可以使用DoAndReturn方法并在一个EXPECT中返回您想要的值。我无法写入类型,因为我不知道方法签名。

代码语言:javascript
复制
    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
            }
        })
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72325840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档