Reputation: 621
I have a Singleton class that I want to test. It uses a @Inject annotation for that class's contructor. Now for testing I want to call a public method for that class in my test class but unable to do so. I have mocked an object that is getting passed to the constructor.
@Inject
private SomeClass(SomeOtherClassObject obj) {
super(obj);
}
I mocked the above private constructor in the following way:
Singleton mockSingleton = PowerMock.createMock(Singleton.class);
PowerMock.expectNew(Singleton.class).andReturn(mockSingleton);
I dont understand how do I call the following method
public SomeClass someMethod(int 1, String 2){
//some logic
return (Object of SomeClass)
}
Any help will be appreciated. Thank You.
Upvotes: 1
Views: 169
Reputation: 11993
If you are using guice as well, you can provide a module in your test that binds SomeOtherClassObject to your mock instance. Then create the SomeClass instance via Guice's injector.
@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(...);
}
If you dont use guice, have a look at needle4j. Its a test-support lib that automatically injects mocks when injection is required. But it works only with easymock or mockito.
Upvotes: 1