开发者

java.sql.Driver stub not being recognized by java.sql.DriverManger

开发者 https://www.devze.com 2023-03-22 02:07 出处:网络
I am trying to unit test a thin data access layer that I\'ve written. I was hoping I wouldn\'t have to inject a stub of DriverManager into the class that makes the connection, and I don\'t have a mock

I am trying to unit test a thin data access layer that I've written. I was hoping I wouldn't have to inject a stub of DriverManager into the class that makes the connection, and I don't have a mock framework available. I have check my implementation against MockRunner's MockDriver and it is very similar, but when I run the test I get a SQLException: "No suitable driver found for jdbc:mysql://localhost:3306." Here is the stub code:

public class DriverStub implements Driver
{
    @Override
    public boolean acceptsURL(String URL) throws SQLException
    {
        return true;
    }
    @Override
    public Connection connect(String url, Properties info) throws SQLException
    {
        return new ConnectionStub();
    }
    @Override
    public int getMajorVersion()
    {
        return 1;
    }
    @Override
    public int getMinorVersion()
    {
        return 0;
    }
    @Override
    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
    throws SQLException
    {
        return new DriverPropertyInfo[0];
    }
    @Override
    public boolean jdbcCompliant()
    {
        return true;
    }
}

A fragment of the calling code:

Connection connection = null;
try
{
    Class.forName(driver).newInstance();
}
...
try
{
 开发者_C百科   connection = Drivermanager.getConnection(...);
}
...


The Driver implementation should register an instance of the Driver through DriverManager.registerDriver in its static initialiser.

public class DriverStub implements Driver {
    static {
        java.sql.DriverManager.registerDriver(new DriverStub());
    }
    ...
}

It's a complete and utter hack, but there you go. Personally, I'd suggest ignoring DriverManager and linking directly to the driver.


This seems to be far more effort than it's worth. Why would you want to stub the DriverManager? What does that test? How do you prove the worth of your data access layer by not using a real driver manager? Don't you want to connect to a database to test?

I'd load the JDBC driver and be done with it. This seems like mocking run amok to me.

0

精彩评论

暂无评论...
验证码 换一张
取 消