使用PowerMockito模拟界面

时间:2016-12-15 07:34:25

标签: java unit-testing mockito powermock

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

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

请在以下链接中找到Connection界面的源代码

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);

这是正确的嘲弄形式,因为它无法正常工作

1 个答案:

答案 0 :(得分:1)

要模拟static方法,您需要:

  1. 在课程或方法级别添加@PrepareForTest
  2. 示例:

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

      PowerMockito.mockStatic(Static.class);
      
      1. 只需使用Mockito.when()来设定您的期望:
      2. 示例:

        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

        的更多详情