嘲弄
static
方法,您需要:
-
添加
@PrepareForTest
在类或方法级别。
例子:
@PrepareForTest(Static.class) // Static.class contains static methods
-
Call PowerMockito.mockStatic(class)
要模拟静态类(使用
PowerMockito.spy(class)
模拟特定方法):
例子:
PowerMockito.mockStatic(Static.class);
-
只是使用
Mockito.when()
要设置您的期望值:
例子:
Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
因此,在您的情况下,可能是这样的:
@RunWith(PowerMockRunner.class)
public class ConnectionFactoryTest {
@Test
@PrepareForTest(ConnectionFactory.class)
public void testConnection() throws IOException {
Connection mockconnection = PowerMockito.mock(Connection.class);
PowerMockito.mockStatic(ConnectionFactory.class);
PowerMockito.when(ConnectionFactory.createConnection()).thenReturn(mockconnection);
// Do something here
}
}
更多详情
how to mock a static method