-
I've build a simple app using fx. It's a simple New-Provide-Invoke structure: app := fx.New(
fx.Provide(service.NewServiceA),
fx.Provide(service.NewServiceB),
fx.Invoke(runHTTPListener),
) ...where I find that https://github.com/uber-go/fx/tree/master/fxtest is somewhat hard to follow, but I'd like to know that in the unit test for Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
To unit test just func TestServiceB(t *testing.T) {
mockServiceA := // ...
NewServiceB(mockServiceA)
// ...
} However, to test ServiceB integration with Fx, you can use func opts() fx.Option {
return fx.Options(
fx.Provide(service.NewServiceA),
fx.Provide(service.NewServiceB),
fx.Invoke(runHTTPListener),
)
}
func main() {
app := fx.New(opts()...)
// ...
} With this, you can test a few different things. Verify dependenciesYou can test just that all dependencies are supplied and present with the help of fx.ValidateApp. func TestDependenciesAreSatisfied(t *testing.T) {
if err := fx.ValidateApp(opts()); err != nil {
t.Error(err)
}
} We include a similar test in most of our services internally. Integration testIf you want to write an integration test for any component, you can use For example, func TestServiceB(t *testing.T) {
app := fxtest.New(t,
opts(),
fx.Decorate(newFakeServiceA), // returns ServiceA
)
// Starts the app right away, and defers a stop when the test ends.
defer app.RequireStart().RequireStop()
// TODO: make a request to the app
} In this example, we replace the ServiceA consumed by ServiceB with a fake so that the real ServiceA is not instantiated. |
Beta Was this translation helpful? Give feedback.
To unit test just
ServiceB
, you can write a unit test that callsNewServiceB
directly—like a regular function.However, to test ServiceB integration with Fx, you can use
fxtest
.For this, you need to either duplicate the list of arguments to
fx.New
, or extract them into a helper function.Internally, most of our applications have a helper
opts() fx.Option
function that looks like this:W…