首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何模拟在Golang测试中进行外部调用的中间件?

如何模拟在Golang测试中进行外部调用的中间件?
EN

Stack Overflow用户
提问于 2022-03-21 14:31:48
回答 1查看 593关注 0票数 0

TLDR:有一个go-chi中间件正在进行外部调用以授权请求。我需要嘲笑它的作用。

详细信息:

我有个测试:

代码语言:javascript
复制
func Test_HTTP_UserSet_Create_InvalidAction(t *testing.T) {
    requestBody :=
        `{
            "name": "test",
            "action": "TEST"
        }`

    req, _ := http.NewRequest("POST", "/1234/users", bytes.NewBuffer([]byte(requestBody)))

    recorder := setupInvalidActionRecorder(t, req)

    if status := recorder.Code; status != http.StatusBadRequest {
        t.Errorf("Status code expected to be %d but got %d", http.StatusBadRequest, status)
        return
    }
}

上面的setupUnknownErrorRecorder是:

代码语言:javascript
复制
func setupUnknownErrorRecorder(t *testing.T, request *http.Request) *httptest.ResponseRecorder {
    recorder := httptest.NewRecorder()

    c := resty.New()

    resource := users.NewResource(
        httpClient.NewHttpClient(log, &config.Server{}, &logger.LogRecord{}, c),
    )

    resource.Routes().ServeHTTP(recorder, request)

    return recorder
}

我得到的结果是:

代码语言:javascript
复制
=== RUN   Test_HTTP_UserSet_Create_InvalidAction
    invalidAction_test.go:71: Status code expected to be 400 but got 401
--- FAIL: Test_HTTP_UserSet_Create_InvalidAction (0.00s)

这个结果是预期的,因为服务器正在使用我传递给NewResource的客户端NewResource进行外部调用。

有一个go-chi中间件正在使用这个客户端进行外部调用。

我的问题是:我怎样才能让这个http电话总是返回200,而没有真正的打电话。也就是怎么嘲弄这个电话?

编辑:上面的httpClient接口是:

代码语言:javascript
复制
type HttpClient struct {
    logger          *logger.Logger
    config          *config.Server
    instrumentation *instrumentation
    record          *logger.LogRecord
    restyClient     *resty.Client
}

func NewHttpClient(
    logger *logger.Logger,
    config *config.Server,
    record *logger.LogRecord,
    restyClient *resty.Client,
) HttpClient {
    return HttpClient{
        instrumentation: newInstrumentation(logger, record),
        config:          config,
        logger:          logger,
        record:          record,
        restyClient:     restyClient,
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-23 08:20:55

可测试代码的一个非常基本的规则是,您不能只在其他服务中创建新服务。您需要注入它,如果已经没有resty.New返回的任何内容,则需要准备一个接口。这样你就可以在测试中注入你的模拟。

然后,您可以使用https://pkg.go.dev/github.com/stretchr/testify/mock生成模拟,并表示模拟服务应该返回的值是什么。

评论后的最新情况:

代码语言:javascript
复制
type HttpClient struct {
    logger          *logger.Logger
    config          *config.Server
    instrumentation *instrumentation
    record          *logger.LogRecord
    restyClient     *resty.Client // <- this is the thing you want to change from a pointer to resty.Client to an interface
}

检查代码中使用的restyClient方法,并创建包含它们的新接口,如下所示:

代码语言:javascript
复制
type MyRestyClient interface {
   FirstUsedMethod(..)
   
   ...
}

并将restyClient声明交换为

代码语言:javascript
复制
type HttpClient struct {
    ...
    restyClient     MyRestyClient

在此之后,您可以使用我之前通过命令粘贴的链接中的嘲弄来为您生成一个模拟。

稍后,您只需在测试中安装模拟:

代码语言:javascript
复制
restyMock := new(RestyMock)
restyMock.On("MethodYouExpect").Return(returnValueOfYourChoice)

然后你在测试下把准备好的模拟注入到你的服务中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71559295

复制
相关文章

相似问题

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