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>

最佳答案

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

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

07-26 00:48