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
{
connection = Drivermanager.getConnection(...);
}
...
The
Driverimplementation should register an instance of theDriverthrough DriverManager.registerDriver in its static initialiser.It’s a complete and utter hack, but there you go. Personally, I’d suggest ignoring
DriverManagerand linking directly to the driver.