Java - 代码覆盖率

Dam*_*ien 5 java unit-testing code-coverage

我在我的代码库中的一个类中有一个方法,对于我的生活,我无法进行我的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;
}}
Run Code Online (Sandbox Code Playgroud)

知道如何确保我的junit测试执行if语句吗?我目前正在使用EasyMock和Powermock,但如果使用这些工具进行判断,我找不到进入此方法的方法

非常感谢所有帮助

谢谢Damien

Pét*_*rök 8

您应该重构您的类以成为另一个数据源的代理,而不是从一个数据源继承.通过这种方式,您可以轻松地向其中注入模拟数据源而不是真实数据源.

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;
  }
}
Run Code Online (Sandbox Code Playgroud)