【问题标题】:Mock an interface using PowerMockito使用 PowerMockito 模拟界面
【发布时间】:2017-04-30 17:37:45
【问题描述】:

我需要在 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);

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

【问题讨论】:

  • 你是否在测试的顶部添加了@RunWith(PowerMockRunner.class) 和@PrepareForTest(ConnectionFactory.class)?

标签: java unit-testing mockito powermock


【解决方案1】:

要模拟 static 方法,您需要:

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

例子:

@PrepareForTest(Static.class) // Static.class contains static methods
  1. Call PowerMockito.mockStatic(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的详情

【讨论】:

  • 嗨@Nicolas Filotto 我已经编辑了我的问题,并且在新编辑后我有一些疑问。
  • 请为其创建一个新问题
  • 嗨@Nicolas Filotto 请在这里找到问题stackoverflow.com/questions/41165788/…
  • @Reddevil 完美,我得走了,如果你没有答案,我会尽快回复,然后再回来
  • 不,我没有任何问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多