简体   繁体   中英

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!

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);

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM