我有興趣創建一個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)
- 1 回答
- 0 關注
- 123 瀏覽
添加回答
舉報
0/150
提交
取消