使用 PowerMockito 模拟界面

Mock an interface using PowerMockito

我需要在 hbase api 中模拟一个方法。请在下面找到方法

 public static Connection createConnection() throws IOException {
    return createConnection(HBaseConfiguration.create(), null, null);
 }

Connection接口的源代码请见下方link

http://grepcode.com/file/repo1.maven.org/maven2/org.apache.hbase/hbase-client/1.1.1/org/apache/hadoop/hbase/client/Connection.java

我试过如下

Connection mockconnection = PowerMockito.mock(Connection.class);
PowerMockito.when(ConnectionFactory.createConnection()).thenReturn(mockconnection);

这是正确的模拟形式吗,因为它不能正常工作

要模拟 static 方法,您需要:

  1. 在 class 或方法级别添加 @PrepareForTest

示例:

@PrepareForTest(Static.class) // Static.class contains static methods
  1. Call PowerMockito.mockStatic(class) 模拟静态 class(使用 PowerMockito.spy(class) 模拟特定方法):

示例:

PowerMockito.mockStatic(Static.class);
  1. 只需使用 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

的更多详细信息