Java 使用PowerMockito模拟接口
我需要在hbase API中模拟一个方法。请找到下面的方法Java 使用PowerMockito模拟接口,java,unit-testing,mockito,powermock,Java,Unit Testing,Mockito,Powermock,我需要在hbase API中模拟一个方法。请找到下面的方法 public static Connection createConnection() throws IOException { return createConnection(HBaseConfiguration.create(), null, null); } 请在下面的链接中找到连接接口的源代码 我试过如下方法 Connection mockconnection = PowerMockito.mock(Connec
public static Connection createConnection() throws IOException {
return createConnection(HBaseConfiguration.create(), null, null);
}
请在下面的链接中找到连接接口的源代码
我试过如下方法
Connection mockconnection = PowerMockito.mock(Connection.class);
PowerMockito.when(ConnectionFactory.createConnection()).thenReturn(mockconnection);
这种模拟形式是否正确,因为它无法正常工作要模拟静态
方法,您需要:
@PrepareForTest
调用PowerMockito.mockStatic(class)
模拟静态类(使用PowerMockito.spy(class)
模拟特定方法):Mockito.when()
设置您的期望值:所以在您的情况下,应该是这样的:
@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
}
}
有关的更多详细信息,您是否已将@RunWith(PowerMockRunner.class)和@PrepareForTest(ConnectionFactory.class)添加到测试顶部?您好@Nicolas Filotto我已编辑了我的问题,我有一些在新编辑后提到的问题。请为itHi@Nicolas Filotto创建一个新问题,请在此处找到问题@reddevy perfect,我现在要走了,如果你在我回来之前没有任何答案,我会尽快回答你不,我没有任何问题
PowerMockito.mockStatic(Static.class);
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
}
}