I am trying to use a power mock to mock a class with @Injects and static methods called in another class constructor. But for some reason it seems to be throwing MissingMethodInvocationException in PowerMockito.when.
@Named
public class InstanceLocationWrapperFactory {
@Inject
private InstanceLocation instanceLocation;
private static InstanceLocation internalInstanceLocation;
@PostConstruct
private void load(){
internalInstanceLocation = instanceLocation;
}
public static InstanceLocation getInstance(){
return internalInstanceLocation;
}
}
I am trying to use it to instantiate a value inside the constructor of another class like as follows. (InstanceLocation is a interface which is implemented by DefaultInstanceLocationImpl class.)
class A{
InstanceLocation instance;
A(){
instance = InstanceLocationWrapperFactory.getInstance();
}
public String myMethod(){
/* using instance here to do some logic*/
}
}
I am trying to write a test like this
@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, InstanceLocationWrapperFactory.class})
public class ATest {
@Test
public void myTestCase1{
InstanceLocation instanceLocation = mock(DefaultInstanceLocationImpl.class);
PowerMockito.mockStatic(InstanceLocationWrapperFactory.class);
PowerMockito.when(InstanceLocationWrapperFactory.getInstance()).thenReturn(instanceLocation);
when(instance.getMethod()).thenReturn("something");
}
But when i run the above code for some reason i keep getting the below error for the line PowerMockito.when(InstanceLocationWrapperFactory.getInstance()).thenReturn(instanceLocation);.
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
Can someone please help me understand if I am doing something wrong or missing something here.