登录
首页 >  Golang >  Go问答

实现Golang测试中的外部调用中间件模拟

来源:stackoverflow

时间:2024-02-13 09:18:25 347浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《实现Golang测试中的外部调用中间件模拟》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

tldr:有一个 go-chi 中间件正在发出外部调用来授权请求​​。我需要模拟它的作用。

详细信息:

我有这个测试:

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是:

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
}

我得到的结果是:

=== 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 的客户端 c 进行外部调用。

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

我的问题是:如何让这个 http 调用始终返回 200,而不真正进行调用。又名如何模拟这个调用?

编辑: 上面httpclient的接口是:

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

正确答案


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

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

评论后更新:

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 的哪些方法,并创建包含它们的新接口,如下所示:

type myrestyclient interface {
   firstusedmethod(..)
   
   ...
}

并将restyclient声明交换为

type httpclient struct {
    ...
    restyclient     myrestyclient

之后,您可以使用我之前粘贴的链接中的模拟,并通过命令为您生成模拟。

稍后,您只需在测试中设置模拟:

restyMock := new(RestyMock)
restyMock.On("MethodYouExpect").Return(returnValueOfYourChoice)

然后您将准备好的模拟注入到您的测试服务中。

以上就是《实现Golang测试中的外部调用中间件模拟》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>