-
Notifications
You must be signed in to change notification settings - Fork 33
Description
To demonstrate the problem, I made a toy project with these classes:
@Singleton
public class InjectedClass {
private static int instanceCount = 0;
public InjectedClass() {
instanceCount++;
}
}
public class InjectionReceiver {
private static int instanceCount = 0;
private static int injectCount = 0;
public InjectionReceiver() {
instanceCount++;
}
@Inject
public void inject(InjectedClass injectedObject) {
injectCount++;
}
}
public class InjectingModule extends AbstractModule {
@Override
protected void configure() {
requestInjection(new InjectionReceiver());
}
}
and this test:
@RunWith(JukitoRunner.class)
public class InjectTest {
public static class Module extends JukitoModule {
@Override
protected void configureTest() {
install(new InjectingModule());
}
}
@Test
public void test(InjectedClass injectedObject) {
int a = 1;
}
}
When I run the test with break points to follow the execution flow, InjectTest runs its module configuration twice (annoying, but mostly ignorable), which creates two InjectionReceiver objects and requests that each of them get injected. The first never gets injected, I suspect because it gets thrown away and garbage collected.
After this, one instance of InjectedClass is created and passed in to the second InjectionReceiver instance's inject method. Then another instance of InjectedClass is created and that instance is passed in to InjectTest.test. This is a bug.
In my production code, Guice creates only a single instance of the InjectedClass analog, and that same instance is passed in to both the InjectionReceiver.inject analog and every other place the class is called for. This is working correctly, and my code depends on this behavior to function.
In order for my tests to work, they have to have the same instance that is passed in to InjectionReceiver.inject, and they aren't getting it.