Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice injector in JUnit tests [closed]

Using Guice, is it a good practice to get a new injector in each JUnit test class, as each test class should be independant?

like image 245
Alexis Dufrenoy Avatar asked Sep 04 '25 16:09

Alexis Dufrenoy


2 Answers

In case anyone stumbles upon this question and wants to see how to get Guice annotations working from unit tests, extend your tests from a base class like the one below and call injector.injectMembers(this);

public class TestBase {
    protected Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bind(HelloService.class);
        }
    });

    @Before
    public void setup () {
        injector.injectMembers(this);
    }
}

Then your test can get an injected HelloService like this

public class HelloServiceTest extends TestBase {
    @Inject
    HelloService service;

    @Test
    public void testService() throws Exception {
       //Do testing here
    }
}
like image 65
Joe Abrams Avatar answered Sep 07 '25 09:09

Joe Abrams


You should really avoid using Guice in unit tests as each test should be small enough that manual DI is manageable. By using Guice (or any DI) in unit tests you are hiding away a warning that your class is getting too big and taking on too many responsibilities.

For testing the bootstrapper code and integration tests then yes create a different injector for each test.

like image 31
Michael Lloyd Lee mlk Avatar answered Sep 07 '25 07:09

Michael Lloyd Lee mlk