I am having some issues with a jukito unit test. I can't seem to mock Provider. Examples:.
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
@Singleton
public class ServiceClass1 {
@Inject
Provider<ConnectionClass> provider;
public void method1() {
Object o = provider.get().getO(); //during mainTest, provider is null and I get Nullpointer
}
}
@Singleton
public class ConnectionClass {
public Object getO() {
//this is not relevant
}
}
public class ConfigurationModule extends AbstractModule {
bind(ServiceClass1.class).in(Singleton.class);
bind(ConnectionClass.class).in(Singleton.class);
}
@RunWith(JukitoRunner.class)
public class ServiceClass1Test {
@InjectMocks
ServiceClass1 service;
@Mock
Provider<ConnectionClass> connectionClassProvider;
@Mock
ConnectionClass connectionClass;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(connectionClassProvider.get()).thenReturn(connectionClass);
}
@Test
public void mainTest() {
service.method1();
}
}
I expect to get a mocked connection class, but instead provider returns null. I tried binding connectionClass to TestSingleton, but that does not help. Inside test class:
public static class Module extends JukitoModule {
@Override
protected void configureTest() {
bindMock(ConnectionClass.class).in(TestSingleton.class);
}
}
If anyone has some suggestions for me, I would greatly appreciate it.
Using constructor injection instead of field injection:
@Singleton
public class ServiceClass1 {
Provider<ConnectionClass> provider;
@Inject
public ServiceClass1(Provider<ConnectionClass> provider) {
this.provider = provider;
}
}
and dropping InjectMocks:
@Mock
Provider<ConnectionClass> provider;
ServiceClass1 serviceClass1;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
serviceClass1 = new ServiceClass1(provider);
}
makes everything work. Can InjectMocks be the cause of this? Anyway, I guess this will do for now.