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>
答案 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");