Highlight one static method using PowerMock and TestNG

class StaticClass {
  public static String a(){ return "a"; }
  public static String ab(){ return a()+"b"; }
}

I want to make fun of StaticClass::ahim returning "x", and the call StaticClass.ab()leads to "xb"...

I find it very difficult to work in PowerMock and TestNG ...


The exact code I'm testing 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>
+4
source share
2 answers

Why not try something like:

PowerMockito.mockStatic(StaticClass.class);
Mockito.when(StaticClass.a()).thenReturn("x");
Mockito.when(StaticClass.ab()).thenCallRealMethod();
+5
source

I think this can be accomplished with Partial Mock.

PowerMock.mockStaticPartial(Mocked.class, "methodToBeMocked");

This may help: http://avricot.com/blog/index.php?post/2011/01/25/powermock-%3A-mocking-a-private-static-method-on-a-class

+2
source

All Articles