猿问

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

我有兴趣创建一个httptest.Server简单地记录调用它的请求。为此,我想使用该github.com/matryer/moq库。


为了生成一个模拟http.Handler,我将它的定义复制到一个名为的包中client:


package client


import "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/moq


package client


import (

    "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

        }

    }

}


以制作具有模拟处理程序函数的测试服务器?


Cats萌萌
浏览 135回答 1
1回答

慕田峪7331174

错误消息是说你HandlerMock没有实现接口http.Handler。但是,*HandlerMock确实实现了它:func (mock *HandlerMock) ServeHTTP(in1 http.ResponseWriter, in2 *http.Request)尝试将语句更改ts := httptest.NewServer(handlerMock)为ts := httptest.NewServer(&handlerMock)
随时随地看视频慕课网APP

相关分类

Go
我要回答