class StaticClass {
public static String a(){ return "a"; }
public static String ab(){ return a()+"b"; }
}
I want to mock StaticClass::a
so that it returns "x"
and the call to StaticClass.ab()
results in "xb"
...
I find it very hard in PowerMock and TestNG...
the exact code I am testing righ now:
class StaticClass {
public static String A() {
System.out.println("Called A");
throw new IllegalStateException("SHOULD BE MOCKED AWAY!");
}
public static String B() {
System.out.println("Called B");
return A() + "B";
}
}
@PrepareForTest({StaticClass.class})
public class StaticClassTest extends PowerMockTestCase {
@Test
public void testAB() throws Exception {
PowerMockito.spy(StaticClass.class);
BDDMockito.given(StaticClass.A()).willReturn("A");
assertEquals("AB", StaticClass.B()); // IllegalStateEx is still thrown :-/
}
}
I have Maven dependencies on:
<artifactId>powermock-module-testng</artifactId>
and
<artifactId>powermock-api-mockito</artifactId>
Why not try something like :
PowerMockito.mockStatic(StaticClass.class);
Mockito.when(StaticClass.a()).thenReturn("x");
Mockito.when(StaticClass.ab()).thenCallRealMethod();
I think this can be accomplished with a Partial Mock.
PowerMock.mockStaticPartial(Mocked.class, "methodToBeMocked");
This might be of help: http://avricot.com/blog/index.php?post/2011/01/25/powermock-%3A-mocking-a-private-static-method-on-a-class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With