1

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 ?

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Eko
  • 1,487
  • 1
  • 18
  • 36
  • 1
    Possible duplicate of [PowerMock, mock a static method, THEN call real methods on all other statics](http://stackoverflow.com/questions/14651138/powermock-mock-a-static-method-then-call-real-methods-on-all-other-statics) – kan May 02 '17 at 14:34

1 Answers1

1

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

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63