我在我的代码库中的一个类中有一个方法,在我的生命中,我不能进入我的junit测试。基本上,当我请求一个数据库连接时会调用这个类,如果返回一个过时的连接,就会建立一个新的连接
下面是我的类中方法的代码片段(为此目的而进行了裁剪)
public class TCSOracleDataSourceWrapper extends OracleDataSource {
private static final int STALE_CONNECTION_EX_CODE = 17143;
private OracleConnectionCacheManager cacheManager;
private String cacheName;
/** Local log variable **/
private final Log logger = LogFactory.getLog(getClass());
/**
* Class constructor
* @throws SQLException
*/
public TCSOracleDataSourceWrapper() throws SQLException {
super();
}
private static final long serialVersionUID = 1L;
@Override
/**
* Get a connection but if the connection is stale then refresh all DB connections
*
*/
public final Connection getConnection() throws SQLException {
logger.debug("Retrieving a database connection from the pool");
Connection connection = null;
try{
connection = super.getConnection();
}
catch(SQLException e)
{
if(e.getErrorCode() == STALE_CONNECTION_EX_CODE)
{
logger.error("Stale Oracle connection found in the Connection Pool. Refreshing invalid DB connections.");
//refresh invalid connections
cacheManager.refreshCache(cacheName, OracleConnectionCacheManager.REFRESH_INVALID_CONNECTIONS);
//now try to get the connection again
connection = super.getConnection();
}
else
{
throw e;
}
}
return connection;
}}你知道如何确保我的junit测试执行if语句吗?我目前正在使用EasyMock和Powermock,但是我找不到一种方法来使用这些工具来实现这个if语句
非常感谢您的帮助。
谢谢你,达米恩
发布于 2011-09-02 00:26:18
您应该重构您的类,使其成为另一个数据源的,而不是从一个数据源继承。通过这种方式,您可以轻松地向其中注入一个模拟数据源,而不是真正的数据源。
import javax.sql.DataSource;
public class TCSOracleDataSourceWrapper implements DataSource {
...
private DataSource wrappedDataSource;
...
public TCSOracleDataSourceWrapper(DataSource ds) {
wrappedDataSource = ds;
}
...
public final Connection getConnection() throws SQLException {
...
Connection connection = null;
try{
connection = ds.getConnection();
}
catch(SQLException e)
{
...
}
return connection;
}
}发布于 2011-09-02 00:27:07
脑海中浮现出一个想法:使用聚合而不是继承。这个问题和其他类似的问题将会消失,因为您可以模拟聚合对象,使其具有您想要的任何行为。我看不到另一种方法可以马上进去。实际上,名称TCSOracleDataSourceWrapper已经表明它包装了一个数据源(聚合),而实际上并不是。
发布于 2011-09-02 00:37:02
一种快速的解决方法是将super.getConnection()调用排除在一个新的私有/受保护方法中。一旦进行了更改,就可以很容易地使用power mock来模拟getBaseConnection方法。这是短期的解决方法,就像其他答案建议的那样,对于包装器实现,最好使用委托而不是继承。
Connection getBaseConnection() throws SQLException {
return super.getConnection();
}
public final Connection getConnection() throws SQLException {
logger.debug("Retrieving a database connection from the pool");
Connection connection = null;
try{
connection = getBaseConnection();
}
catch(SQLException e)
{
if(e.getErrorCode() == STALE_CONNECTION_EX_CODE)
{
logger.error("Stale Oracle connection found in the Connection Pool. Refreshing invalid DB connections.");
//refresh invalid connections
cacheManager.refreshCache(cacheName, OracleConnectionCacheManager.REFRESH_INVALID_CONNECTIONS);
//now try to get the connection again
connection = getBaseConnection();
}
else
{
throw e;
}
}
return connection;
}https://stackoverflow.com/questions/7273271
复制相似问题