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

Par*_*bay 4 java testng mocking powermock

class StaticClass {
  public static String a(){ return "a"; }
  public static String ab(){ return a()+"b"; }
}
Run Code Online (Sandbox Code Playgroud)

我想模仿,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 :-/
    }

}
Run Code Online (Sandbox Code Playgroud)

我有Maven依赖:

<artifactId>powermock-module-testng</artifactId>
and
<artifactId>powermock-api-mockito</artifactId>
Run Code Online (Sandbox Code Playgroud)

use*_*425 7

为什么不尝试类似的东西:

PowerMockito.mockStatic(StaticClass.class);
Mockito.when(StaticClass.a()).thenReturn("x");
Mockito.when(StaticClass.ab()).thenCallRealMethod();
Run Code Online (Sandbox Code Playgroud)

  • 如果该方法不返回任何内容(void),这仍然可能吗?我的静态类有 20 个静态方法,而我只想模拟其中一种方法怎么样? (2认同)

abo*_*g28 2

我认为这可以通过部分模拟来完成。

PowerMock.mockStaticPartial(Mocked.class, "methodToBeMocked");
Run Code Online (Sandbox Code Playgroud)

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