我已经整理了一段代码,它在我的路线上执行 GET。我想使用模拟来测试它。我是围棋和测试新手,因此非常感谢任何提示。
我的 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)
}
我的疑惑:
考虑到我正在尝试注入依赖项,这里的模拟是如何工作的?
我应该从哪里开始测试,即我应该在 Generate Routes 中模拟 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
}
我参考过的链接: