Reputation: 61
I have to write a unit test for a static method which requires mocking another static method of the same class. Sample code:
public class A {
public static boolean foo(){}
public static boolean bar(){
return foo();
}
}
@PrepareForTest({A.class})
public ATest{
testMethod(){
mockStatic(A.class);
when(A.foo()).thenReturn(true);
assertTrue(A.bar());
}
}
I have been trying to unit test the bar method but so far not been successful.
Issue: Debug doesn't reach the return foo();
statement in my code and assertion fails. Please advice. I cannot modify the code at this point of time
Any help in mocking the foo method would be appreciated.Thanks!
Upvotes: 5
Views: 5414
Reputation: 10142
In this scenario, you should not be creating a mock on class but use stub
on only that particular method ( foo()
) from class A
,
public static <T> MethodStubStrategy<T> stub(Method method)
Above method belongs to MemberModifier
class in API and that is a super class of PowerMockito
class so your syntax should look like,
PowerMockito.stub(PowerMockito.method(A.class, "foo")).toReturn(true);
Upvotes: 6
Reputation: 3484
The fact that false
is the default value for boolean
played a bad trick. You were expecting that wrong foo
is called, while in fact bar
was not called. Long story short:
when(A.bar()).thenCallRealMethod();
Upvotes: 3