我正在尝试为调用的方法编写单元测试DriverManager.getConnection()
。我正在使用 PowerMock 1.5 和 easymock。不知何故,Powermock 无法模拟 DriverManager 并最终调用真正的 DriverManager。这就是我的代码的样子:-
@Test
public void checkConnection() {
try {
String url = "jdbc:oracle:thin:@//myhost:1521/orcl";
String password = "@55";
String dbName = "Halloween";
String username = "Dracula";
PowerMock.mockStatic(DriverManager.class);
Connection connection = EasyMock.createMock(Connection.class);
List<Datasource> allDs = new ArrayList<Datasource>(2);
Datasource d1 = new Datasource();
d1.setUrl(url);
allDs.add(d1);
allDs.add(new Datasource());
EasyMock.expect(hibernateTemplate.find("from Datasource ds where ds.dsName = ?", dbName)).andReturn(allDs);
EasyMock.expect(DriverManager.getConnection(d1.getUrl(), username, password)).andReturn(connection);
PowerMock.replay(DriverManager.class);
EasyMock.replay(hibernateTemplate);
Connection con = testee.authenticateUserForDatabase(dbName, username, password);
Assert.assertNotNull(con);
PowerMock.verify(DriverManager.class);
EasyMock.verify(hibernateTemplate);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
我的课程代码如下所示:-
@Override
public Connection getConnection(String dbName, String username, String password) {
Connection connection = null;
@SuppressWarnings("unchecked")
List<Datasource> ds = hibernateTemplate.find("from Datasource ds where ds.dsName = ?", dbName);
if (ds == null || ds.isEmpty()) {
throw new ProviderException("Invalid datasource name [" + dbName + "]");
}
Datasource d = (Datasource) ds.get(0);
int retryCount = 0;
boolean connected = false;
while (retryCount < 2 && !connected) {
try {
connection = DriverManager.getConnection(d.getUrl(), username, password);
LOG.info("Connected successfully to [{}]", dbName);
connected = true;
} catch (SQLException e) {
LOG.warn("Error: [{}] occured. Going to retry, attempt # [{}]", e.getMessage(), (retryCount + 1));
retryCount++;
connected = false;
}
}
return connection;
}