I’m writing a new go application and ended up giving fx (by uber) a try for dependency injection. The getting started docs were brilliant for my use case (creating an API), but the examples for how to inject mock services for tests were lacking, so I decided to write some code examples of how I am currently using fx in tests.
General app setup
I set up my whole application in a app package, which pulls in all services that are needed.
Most of these are provided as constructor functions, with some more dynamic registration of routes as is done in the getting started docs.
package app
func New(additionalOpts ...fx.Option) *fx.App {
return fx.New(
fx.Provide(
config.NewDefault,
ses.NewSES,
ses.NewEmailSender,
mysql.NewGormGB,
middleware.NewLimiterFactory,
middleware.NewAuth,
AsRoute(handlers.UserLogin),
AsRoute(handlers.ListStuff),
fx.Annotate(
router.NewGinRouter,
fx.ParamTags(`group:"routes"`),
),
server.NewHTTPServer,
),
fx.Invoke(func(*http.Server) {}),
fx.Options(additionalOpts...),
)
}Code language: Go (go)




