亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Golang測試中模擬一個進行外部調用的中間件?

如何在Golang測試中模擬一個進行外部調用的中間件?

Go
冉冉說 2022-11-23 19:23:26
有一個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)c這個結果是預期的,因為服務器正在使用我傳遞給的客戶端進行外部調用NewResource。有一個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,    }}
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

可測試代碼的一個非?;镜囊巹t是,您不能只在其他服務中創建新服務。您需要注入它,并準備一個接口(如果返回的內容還沒有接口的話)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)


然后您將準備好的模擬注入到您的測試服務中。


查看完整回答
反對 回復 2022-11-23
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號