用Mockito模拟静态方法 [英] Mocking static methods with Mockito
本文介绍了用Mockito模拟静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个工厂来生产 java.sql.Connection
对象:
I've written a factory to produce java.sql.Connection
objects:
public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {
@Override public Connection getConnection() {
try {
return DriverManager.getConnection(...);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
我想验证传递给 DriverManager.getConnection
的参数,但我不知道如何模拟静态方法。我正在使用JUnit 4和Mockito来测试我的测试用例。有没有一种很好的方法来模拟/验证这个特定的用例?
I'd like to validate the parameters passed to DriverManager.getConnection
, but I don't know how to mock a static method. I'm using JUnit 4 and Mockito for my test cases. Is there a good way to mock/verify this specific use-case?
推荐答案
使用 PowerMockito 。
示例代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class Mocker {
@Test
public void testName() throws Exception {
//given
PowerMockito.mockStatic(DriverManager.class);
BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);
//when
sut.execute();
//then
PowerMockito.verifyStatic();
DriverManager.getConnection(...);
}
更多信息:
- Why does Mockito not mock static methods?
这篇关于用Mockito模拟静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文