Injection in JUnit test

1,991 views
Skip to first unread message

Sydney

unread,
Aug 5, 2011, 6:10:50 PM8/5/11
to gwt-pl...@googlegroups.com
I have a service that I want to test but it requires dependencies. I use Guice

The service:

    @Inject
    public MyService(ObjectDatastore datastore,
            MyDao dao1, OtherDao dao2) {
    }

One Dependency:

    @Inject
    public MyDao(final Provider<ObjectDatastore> datastoreProvider) {
    }

How do you setup Guice to inject the dependency into a JUnit test?

Sydney

unread,
Aug 6, 2011, 5:02:37 PM8/6/11
to gwt-pl...@googlegroups.com
Sometimes I should look by myself before posting the question too quickly on the group. Here is the answer:

        Injector myInjector = Guice.createInjector(new MyTestModule());
        service = myInjector.getInstance(MyService.class);

The test module

public class MyTestModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ObjectDatastore.class).toProvider(
                AnnotationObjectDatastoreProvider.class);
        bind(MyService.class).in(Singleton.class);
    }

}


Magno Machado

unread,
Aug 10, 2011, 8:08:26 AM8/10/11
to gwt-pl...@googlegroups.com
In general, I don't use Guice in tests. I prefer to manually instantiate the class (MyService in your exemple) and pass the dependencies (usualy, mocks) on the constructor myself
--
Magno Machado Paulo
http://blog.magnomachado.com.br
http://code.google.com/p/emballo/

Philippe Beaudoin

unread,
Aug 10, 2011, 9:33:55 AM8/10/11
to gwt-pl...@googlegroups.com
If you like Guice tests, take a look at our other project, Jukito:
I personally love it! :)

Cheers,

   Philippe

visumagic

unread,
Aug 18, 2011, 10:58:12 AM8/18/11
to GWTP
Hi

Could you please provide one sample test case with Actions and
Presenters developed in Jukito.

-raghu

On Aug 10, 6:33 am, Philippe Beaudoin <philippe.beaud...@gmail.com>
wrote:
> If you like Guice tests, take a look at our other project, Jukito:
>  http://jukito.org
> I personally love it! :)
>
> Cheers,
>
>    Philippe
>
>
>
>
>
>
>
> On Wed, Aug 10, 2011 at 8:08 AM, Magno Machado <magn...@gmail.com> wrote:
> > In general, I don't use Guice in tests. I prefer to manually instantiate
> > the class (MyService in your exemple) and pass the dependencies (usualy,
> > mocks) on the constructor myself
>

Christian Goudreau

unread,
Aug 18, 2011, 11:10:33 AM8/18/11
to gwt-pl...@googlegroups.com
Here's one example from a real app :D


Cheers,
--
Christian Goudreau
Reply all
Reply to author
Forward
0 new messages