为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 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 关注
  • 134 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号