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

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

如何使用 Go 的 moq 模擬 http.Handler?

如何使用 Go 的 moq 模擬 http.Handler?

Go
Cats萌萌 2022-05-05 17:56:22
我有興趣創建一個httptest.Server簡單地記錄調用它的請求。為此,我想使用該github.com/matryer/moq庫。為了生成一個模擬http.Handler,我將它的定義復制到一個名為的包中client:package clientimport "net/http"type Handler interface {    ServeHTTP(http.ResponseWriter, *http.Request)}然后我跑了moq -out handler_mock.go . Handler在client目錄中,它產生了以下內容handler_mock.go:// Code generated by moq; DO NOT EDIT.// github.com/matryer/moqpackage clientimport (    "net/http"    "sync")var (    lockHandlerMockServeHTTP sync.RWMutex)// Ensure, that HandlerMock does implement Handler.// If this is not the case, regenerate this file with moq.var _ Handler = &HandlerMock{}// HandlerMock is a mock implementation of Handler.////     func TestSomethingThatUsesHandler(t *testing.T) {////         // make and configure a mocked Handler//         mockedHandler := &HandlerMock{//             ServeHTTPFunc: func(in1 http.ResponseWriter, in2 *http.Request)  {//                 panic("mock out the ServeHTTP method")//             },//         }////         // use mockedHandler in code that requires Handler//         // and then make assertions.////     }type HandlerMock struct {    // ServeHTTPFunc mocks the ServeHTTP method.    ServeHTTPFunc func(in1 http.ResponseWriter, in2 *http.Request)    // calls tracks calls to the methods.    calls struct {        // ServeHTTP holds details about calls to the ServeHTTP method.        ServeHTTP []struct {            // In1 is the in1 argument value.            In1 http.ResponseWriter            // In2 is the in2 argument value.            In2 *http.Request        }    }}以制作具有模擬處理程序函數的測試服務器?
查看完整描述

1 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

錯誤消息是說你HandlerMock沒有實現接口http.Handler。但是,*HandlerMock確實實現了它:

func (mock *HandlerMock) ServeHTTP(in1 http.ResponseWriter, in2 *http.Request)

嘗試將語句更改ts := httptest.NewServer(handlerMock)ts := httptest.NewServer(&handlerMock)


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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