Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a single static method using PowerMock and TestNG

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>
like image 900
Parobay Avatar asked Dec 05 '13 10:12

Parobay


2 Answers

Why not try something like :

PowerMockito.mockStatic(StaticClass.class);
Mockito.when(StaticClass.a()).thenReturn("x");
Mockito.when(StaticClass.ab()).thenCallRealMethod();
like image 67
user3575425 Avatar answered Oct 10 '22 09:10

user3575425


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

like image 41
abourg28 Avatar answered Oct 10 '22 08:10

abourg28