Search code examples
javaunit-testingmockitopowermockito

Static method returns empty value


I'm trying to add a test class for a static method :

class SomeClass {

    public static int getLoginPage() {
    if (otherStaticMethod()) {
      return Screen.FOO;
    }
    return Screen.BAR;
  }
}

Note that FOO and BAR have values differents of zero.

My test class :

@RunWith(PowerMockRunner.class)
@PrepareForTest({SomeClass.class})
public class SomeClass_getLoginPage {

  @Test
  public void testgetLoginPage() {    
    PowerMockito.mockStatic(SomeClass.class);    

    Mockito.when(SomeClass.otherStaticMethod()).thenReturn(true);

    assertTrue(SomeClass.getLoginPage() == Screen.FOO);


    Mockito.when(SomeClass.otherStaticMethod()).thenReturn(false);

    assertTrue(SomeClass.getLoginPage() == Screen.BAR);
  }
}

But when the method otherStaticMethod is called, the method getLoginPage returns 0, where it should return FOO or BAR. How can I fix that ?


Solution

  • Just use overloaded spy method instead of actually mocking the entire class.

    PowerMockito.spy(SomeClass.class);
    

    Now by default all the static method will run with real implementation until you actually mock one of them.

    The reason you get 0 is because by mockStatic you mock all the static methods and by default an invocation of an int returning method, would result in that value (if not explicitly specified otherwise).