我在使用 jukito 单元测试时遇到了一些问题。我似乎无法嘲笑提供者。例子:。
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();
}
}
我希望得到一个模拟的连接类,但提供者返回 null。我尝试将 connectionClass 绑定到 TestSingleton,但这没有帮助。内部测试类:
public static class Module extends JukitoModule {
@Override
protected void configureTest() {
bindMock(ConnectionClass.class).in(TestSingleton.class);
}
}
如果有人对我有一些建议,我将不胜感激。