I use PowerMock 1.4.7 and JUnit 4.8.2
I need to mock only some static methods and I want others (from the same class) just to return original value. When I mock with
I managed to use spy and doReturn to achieve it.
class MyStatic {
static String foo() { return "foo"; }
static String foobar() { return foo() + "bar"; }
}
@Test
public void thisShouldSpyStaticMethods() {
// arrange
spy(MyStatic.class);
doReturn("mocked foo").when(MyStatic.class);
MyStatic.foo();
// act
final String result = MyStatic.foobar();
// assert
assertThat(result).isEqualTo("mocked foobar");
}
The doReturn followed by a call to the method to be mocked looks weird (at least to me), but seems to do the trick.
Using spy with when(MyStatic.foo()).thenReturn("mocked foo") doesn't work for me.
PowerMockito's documentation on mocking static method.