Java-用Mockito模拟静态方法
我已经写了一家工厂来生产java.sql.Connection
物体:
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
。有没有模拟或验证此特定用例的好方法?
回答:
在Mockito上使用PowerMockito。
示例代码:
@RunWith(PowerMockRunner.class)@PrepareForTest(DriverManager.class)
public class Mocker {
@Test
public void shouldVerifyParameters() throws Exception {
//given
PowerMockito.mockStatic(DriverManager.class);
BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);
//when
sut.execute(); // System Under Test (sut)
//then
PowerMockito.verifyStatic();
DriverManager.getConnection(...);
}
以上是 Java-用Mockito模拟静态方法 的全部内容, 来源链接: utcz.com/qa/433068.html