Golang 与 Martini:模拟测试示例

Golang with Martini: Mock testing example

我整理了一段代码,可以在我的路线上执行 GET。我想用模拟来测试这个。我是围棋和测试菜鸟,所以非常感谢任何提示。

My Generate Routes.go 为当前 URL 生成路由。 片段:

func (h *StateRoute) GenerateRoutes (router *martini.Router) *martini.Router {
    r := *router

    /**
     * Get all states
     * 
     */
    r.Get("/state",  func( enc app.Encoder,
            db abstract.MongoDB,
            reqContext abstract.RequestContext,
            res http.ResponseWriter,
            req *http.Request) (int, string) {

        states := []models.State{}

        searchQuery := bson.M{}

        var q *mgo.Query = db.GetDB().C("states").Find(searchQuery)
        query, currentPage, limit, total := abstract.Paginate(req, q)
        query.All(&states)

        str, err := enc.EncodeWithPagination(currentPage, limit, total, states)

        return http.StatusOK, app.WrapResponse(str, err)
    })
}

这在我的 server.go 中是这样调用的:

var configuration = app.LoadConfiguration(os.Getenv("MYENV"))

// Our Martini API Instance
var apiInstance *martini.Martini

func init() {

    apiInstance = martini.New()
    // Setup middleware
    apiInstance.Use(martini.Recovery())
    apiInstance.Use(martini.Logger())

    // Add the request context middleware to support contexual data availability
    reqContext := &app.LRSContext{ }
    reqContext.SetConfiguration(configuration)

    producer := app.ConfigProducer(reqContext)
    reqContext.SetProducer(producer)

    apiInstance.MapTo(reqContext, (*abstract.RequestContext)(nil))

    // Hook in the OAuth2 Authorization object, to be processed before all requests
    apiInstance.Use(app.VerifyAuthorization)

    // Connect to the DB and Inject the DB connection into Martini
    apiInstance.Use(app.MongoDBConnect(reqContext))

    // Add the ResponseEncoder to allow JSON encoding of our responses
    apiInstance.Use(app.ResponseEncoder)

    // Add Route handlers
    r := martini.NewRouter()

    stateRouter := routes.StateRoute{}

    stateRouter.GenerateRoutes(&r)

    // Add the built router as the martini action
    apiInstance.Action(r.Handle)
}

我的疑惑:

  1. 考虑到我正在尝试注入依赖项,这里的模拟是如何工作的?

  2. 我应该从哪里开始测试,即我应该在生成路由中模拟 r.Get 吗?现在,我已经做到了这一点,但由于我使用的是处理所有路由和请求的 Martini,如果我所做的是正确的,我会丢失报价?

state_test.go:

type mockedStateRoute struct {
    // How can I mock the stateRoute struct?
    mock.Mock
}
type mockedEncoder struct {
    mock.Mock
}
type mockedMongoDB struct {
    mock.Mock
}
type mockedReqContext struct{
    mock.Mock
}
type mockedRespWriter struct{
    mock.Mock
}
type mockedReq struct{
    mock.Mock
}

func (m *mockedStateRoute) testGetStatesRoute(m1 mockedEncoder,
                    m2 mockedMongoDB, m3 mockedReqContext,
                    m4 mockedReqContext, m5 mockedRespWriter,
                    m6 mockedReq) (string) {
                        args := m.Called(m1,m2,m3,m4,m5,m6)
                        fmt.Print("You just called /states/GET")
                        // 1 is just a test value I want to return
                    return 1, args.Error(1)
}

func TestSomething (t *testing.T) {
    testObj := new(mockedStateRoute)

    testObj.On("testGetStatesRoute", 123).Return(true,nil)

    // My target function that does something with mockedStateRoute
    // How can I call the GET function in GenerateRoutes(). Or should I, since martini is handling all my requests
}

我提到的链接:

  1. /stretchr/testify/mock doc
  2. examples of 1.

为了进行依赖注入,要测试的东西需要有某种方式来接收它的依赖。在您的代码中,与 mongodb 的连接是在初始化事物以测试自身时完成的,什么不允许注入看起来像 mongo 连接的东西,同时是一个模拟。

实现它的方法有很多种,但是进行依赖注入的最简单和最直接的方法之一就是让要测试的东西在创建时接收依赖,这样它的上下文就是配置依赖的具体实现。看看 this example:

type DataStore interface {
    Get(k string) string
    Set(k, v string)
}

type MyInstance struct {
    *martini.Martini
}

func NewAppInstance(d DataStore) *MyInstance {
    ...
}

func main() {
   d := NewRedisDataStore("127.0.0.1", 6379)
   NewAppInstance(d).Run()
}

该实例需要 Datastore 的实现才能工作,它不需要了解其内部结构,唯一重要的是它实现了接口,具有两种方法,GetSet。事实上,作为单元测试的一般规则,您只想测试您的代码,而不是您的依赖项。在此示例中,它在 "production" 中使用 Redis,但在测试中:

type MockedDataStore struct {
    mock.Mock
}

func (m *MockedDataStore) Get(k string) string {
    args := m.Called(k)
    return args.String(0)
}

func (m *MockedDataStore) Set(k, v string) {
    m.Called(k, v)
}

它只是一些没有任何功能的东西,只是让框架检查它是否已被调用。在测试本身中,您必须使用以下内容配置期望:

d := new(MockedDataStore)
...
d.On("Set", "foo", "42").Return().Once()
...
d.On("Get", "foo").Return("42").Once()

当然,用模拟的东西初始化实例,然后测试它:

d := new(MockedDataStore)
instance := NewAppInstance(d)
d.On("Get", "foo").Return("42").Once()
request, _ = http.NewRequest("GET", "/get/foo", nil)
response = httptest.NewRecorder()
instance.ServeHTTP(response, request)
d.AssertExpectations(t)

因此,作为总结,请更具体地回答您的问题:

  1. 您需要使您的实例能够使用其依赖项进行初始化,例如创建一个接收依赖项和 returns 实例的方法。然后模拟依赖项并从测试中使用模拟而不是 "real" 那些。

  2. 使用martini提供的方法ServeHTTP生成对HTTP请求的响应,httptest.NewRecorder()模拟响应的接收。当然,如果你的应用程序有更复杂的功能,是在 HTTP 接口之外使用的,你也可以像普通方法一样测试它。