gpt4 book ai didi

Java Mocking DriverManager

转载 作者:行者123 更新时间:2023-11-29 08:57:12 26 4
gpt4 key购买 nike

我正在尝试为调用 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;
}

最佳答案

您可以使用 javax.sql.DataSource 而不是 DriverManager。

http://docs.oracle.com/javase/6/docs/api/javax/sql/DataSource.html

这样,您就可以使用可以模拟的界面。现在大多数应用程序都使用 DataSource 接口(interface),而不是像这样与 DriverManager 交互。

所以你的代码可以有一个像这样的 api:

public class DataSourceFactory {
public DataSource getDataSource( String url, String usr, String pwd);
}

如果您愿意,您可以使用 DriverManager 实现真正的 DataSource,然后为您的单元测试模拟 DataSourceFactory。

关于Java Mocking DriverManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com