Hi,
Otherwise you can use a tool to help test units with Guice, Spring,
Jmock, Easymock, Mockito, ... The Guice Plugin supports what you want
i think. Check the last example (example 4)
http://code.google.com/p/mycila/wiki/PluginGuice1.
Guice 1 seems to execute its creation listeners first and in order
(it's a list). So the trick is to provide a first binding in the first
module with something like this. The providers are responsible for
creating your object instances (A, B, ...), and context.getProviders()
keeps a reference on them.
private static interface ProviderSetup {}
bind(ProviderSetup.class).toInstance(new ProviderSetup() {
@Inject
void inject(Injector injector) {
for (Provider<?> provider : context.getProviders()) {
injector.injectMembers(provider);
}
}
});
You can see for example the code at
http://code.google.com/p/mycila/source/browse/mycila-testing/trunk/mycila-testing-plugins/mycila-testing-guice/src/main/java/com/mycila/testing/plugin/guice/Guice1TestPlugin.java
Mathieu.
On Jan 13, 6:34 am, mathias <[email protected]> wrote:
> Gentlemen,
>
> I would like to propose a small extension to the Binder and/or the
> AbstractModule:
> Consider these cases:
>
> bind(Type.class).toInstance(new A(... some constant parameters...));
>
> In this case Guice will inject members to the instance of A before
> using it for injection.
> All good.
> However, sometimes I am using the following construct to quickly setup
> some dependency chains (e.g. for tests):
> bind(Type.class).toInstance(new A(new B(... some constant
> parameters...)));
>
> In this case Guice will again inject members to the instance of A but
> NOT to the instance of B (because Guice doesn't know anything about
> B).
> This is where the new requestInjection() facility comes in really
> handy.
> However, I have to resort to something rather lengthy like this in
> order to get the job done:
>
> B b = new B(... some constant parameters...);
> requestInjection(b);
> bind(Type.class).toInstance(new A(b));
>
> Now I would prefer to shorten this to:
>
> bind(Type.class).toInstance(new A(injected(new B(... some constant
> parameters...))));
>
> which is easy with the following helper method (which I am currently
> using in my extension to AbstractModule):
>
> protected <T> T injected(T object) {
> requestInjection(object);
> return object;
>
> }
>
> Wouldn't this be a sensible extension which should be in the Binder by
> default?
>
> Thanks for a great addition to the java world!
>
> Cheers,
> Mathias
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/google-guice?hl=en
-~----------~----~----~----~------~----~------~--~---