使用PowerMock和TestNG模拟一个静态方法

时间:2013-12-05 10:56:40

标签: java mocking testng powermock

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

我想模仿StaticClass::a以便它返回"x",而对StaticClass.ab()的调用会导致"xb" ......

我在PowerMock和TestNG中发现它很难......


我正在测试的确切代码:

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 :-/
    }

}

我有Maven依赖:

<artifactId>powermock-module-testng</artifactId>
and
<artifactId>powermock-api-mockito</artifactId>

2 个答案:

答案 0 :(得分:7)

为什么不尝试这样的事情:

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

答案 1 :(得分:2)

我认为这可以通过Partial Mock来实现。

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

这可能会有所帮助:http://avricot.com/blog/index.php?post/2011/01/25/powermock-%3A-mocking-a-private-static-method-on-a-class