Mock a single static method using PowerMock and TestNG

若如初见. 提交于 2020-01-03 15:34:51

问题


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>

回答1:


Why not try something like :

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



回答2:


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



来源:https://stackoverflow.com/questions/20398120/mock-a-single-static-method-using-powermock-and-testng

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!