我正在尝试为称为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接口,并且不会像这样与DriverManager交互。

因此,您的代码将可以具有如下所示的api:

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


然后,您可以根据需要使用DriverManager来实现真正的DataSource,然后模拟DataSourceFactory进行单元测试。

关于java - Java模拟驱动程序管理器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19620345/

10-10 06:54