Retrieve Named/Provided Dependency in DI Graph #919
-
Hi, I'm currently writing an app and I wanted to have some integration tests where I could call the dependencies built with fx. In a Java world with Guice I would do something like this. injector.getInstance (Class<T> type); Is there a way to achieve the same with Fx? I saw this discussion #903 and I saw this piece of code 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
} But this would be only if I put an HTTP server to which I do a request. How can I just call the service methods? This is what I wish I could do. func TestServiceX(t *testing.T) {
app := fxtest.New(t, opts())
defer app.RequireStart().RequireStop()
x, _ := app.GetProvided/Named(X)
result := x.Foo()
//TODO: Assert result contains the expected result
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hello! You can use the fx.Populate API to request objects from the container. var x MyFooer
app := fxtest.New(t,
opts(),
fx.Populate(&x),
)
defer app.RequireStart().RequireStop()
result := x.Foo() Note that the argument must be a pointer to the type of value you're looking up. var foo *Foo
fxtest.New(t,
fx.Provide(NewFoo()), // returns *Foo
fx.Populate(&foo), // **Foo
) You can provide any number of pointers to fill to Pointers will be filled when Design consideration: Why is fx.Populate an argument to fx.New/fxtest.New? Fx intentionally does not allow looking up objects in the App after creation. |
Beta Was this translation helpful? Give feedback.
Hello! You can use the fx.Populate API to request objects from the container.
Note that the argument must be a pointer to the type of value you're looking up.
So if the value inside the container is a
*Foo
, the pointer must be a**Foo
.You can provide any number of pointers to fill to
fx.Populate
.Pointers will be filled when
fx.New
/fxtest.New
returns.However, we recommend calling
app.Start
/app.RequireStart
before using them,because the object might have a dependency …