Guice doesn't support injections into inner classes. It gives an informative error message about why. But, if you try to do the same thing with Jukito, you get little; Jukito will inject a mock of the instance that Guice was not able to create. Here's an example:
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
public class InnerGuiceExample {
public static class Module extends AbstractModule {
@Override
protected void configure() {
bind(String.class).toInstance("hello world!");
}
}
Foo f;
@Before
public void setUp() {
Injector inj = Guice.createInjector(new Module());
f = inj.getInstance(Foo.class);
}
@Test
public void test() {
assertEquals("hello world!", f.toString());
}
public class Foo {
@Inject String test;
public String toString() {
return test;
}
}
}
And Guice's error message:
com.google.inject.ConfigurationException: Guice configuration errors:
1) Injecting into inner classes is not supported. Please use a 'static' class (top-level or nested) instead of com.techemet.server.InnerGuiceExample$Foo.
while locating com.techemet.server.InnerGuiceExample$Foo
1 error
at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1004)
at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:961)
at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1013)
at com.techemet.server.InnerGuiceExample.setUp(InnerGuiceExample.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
Here's the Jukito equivalent of the same code:
import static org.junit.Assert.*;
import org.jukito.JukitoModule;
import org.jukito.JukitoRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Inject;
@RunWith(JukitoRunner.class)
public class InnerJukitoExample {
public static class Module extends JukitoModule {
@Override
protected void configureTest() {
bind(String.class).toInstance("hello world!");
}
}
@Inject Foo f;
@Test
public void test() {
assertEquals("hello world!", f.toString());
}
public class Foo {
@Inject String test;
public String toString() {
return test;
}
}
}
With error message:
org.junit.ComparisonFailure: expected:<[hello world!]> but was:<[Mock for Foo, hashCode: 936146014]>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.techemet.server.InnerJukitoExample.test(InnerJukitoExample.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)