我需要在hbase apis中模拟一个方法。请找到以下方法
public static Connection createConnection() throws IOException {
return createConnection(HBaseConfiguration.create(), null, null);
}
请在以下链接中找到Connection界面的源代码
我试过如下
Connection mockconnection = PowerMockito.mock(Connection.class);
PowerMockito.when(ConnectionFactory.createConnection()).thenReturn(mockconnection);
这是正确的嘲弄形式,因为它无法正常工作
答案 0 :(得分:1)
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
}
}
的更多详情