如何从使用 Google @Inject 的 Singleton class 调用非静态 public 方法
How to call a non static public method from a Singleton class which is using Google @Inject
我有一个 Singleton class 想要测试。它为 class 的构造函数使用 @Inject 注释。现在为了测试,我想在我的测试 class 中为那个 class 调用一个 public 方法,但无法这样做。我模拟了一个传递给构造函数的对象。
@Inject
private SomeClass(SomeOtherClassObject obj) {
super(obj);
}
我通过以下方式模拟了上面的私有构造函数:
Singleton mockSingleton = PowerMock.createMock(Singleton.class);
PowerMock.expectNew(Singleton.class).andReturn(mockSingleton);
我不明白如何调用以下方法
public SomeClass someMethod(int 1, String 2){
//some logic
return (Object of SomeClass)
}
如有任何帮助,我们将不胜感激。谢谢。
如果您也使用 guice,您可以在测试中提供一个模块,将 SomeOtherClassObject 绑定到您的模拟实例。然后通过 Guice 的注入器创建 SomeClass 实例。
@Test
public void test() {
SomeOtherClassObject other = ...; // what ever you need to create the Mock
Injector injector = Guice.createInjector(new AbstractModule(){
public void configure() {
bind(SomeOtherClassObject.class)toInstance(other);
}
});
SomeClass some = injector.getInstance(SomeClass.class); // guice takes care of the constructor injection
some.someMethod(...);
}
如果您不使用 guice,请查看 needle4j。它是一个测试支持库,可在需要注入时自动注入模拟。但它只适用于 easymock 或 mockito。
我有一个 Singleton class 想要测试。它为 class 的构造函数使用 @Inject 注释。现在为了测试,我想在我的测试 class 中为那个 class 调用一个 public 方法,但无法这样做。我模拟了一个传递给构造函数的对象。
@Inject
private SomeClass(SomeOtherClassObject obj) {
super(obj);
}
我通过以下方式模拟了上面的私有构造函数:
Singleton mockSingleton = PowerMock.createMock(Singleton.class);
PowerMock.expectNew(Singleton.class).andReturn(mockSingleton);
我不明白如何调用以下方法
public SomeClass someMethod(int 1, String 2){
//some logic
return (Object of SomeClass)
}
如有任何帮助,我们将不胜感激。谢谢。
如果您也使用 guice,您可以在测试中提供一个模块,将 SomeOtherClassObject 绑定到您的模拟实例。然后通过 Guice 的注入器创建 SomeClass 实例。
@Test
public void test() {
SomeOtherClassObject other = ...; // what ever you need to create the Mock
Injector injector = Guice.createInjector(new AbstractModule(){
public void configure() {
bind(SomeOtherClassObject.class)toInstance(other);
}
});
SomeClass some = injector.getInstance(SomeClass.class); // guice takes care of the constructor injection
some.someMethod(...);
}
如果您不使用 guice,请查看 needle4j。它是一个测试支持库,可在需要注入时自动注入模拟。但它只适用于 easymock 或 mockito。