Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a static method which calls another static method of the same class

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!

like image 365
user3233920 Avatar asked Jan 06 '16 00:01

user3233920


2 Answers

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);
like image 179
Sabir Khan Avatar answered Oct 24 '22 05:10

Sabir Khan


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();
like image 3
user3707125 Avatar answered Oct 24 '22 07:10

user3707125