加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java – 代码覆盖率

发布时间:2020-12-14 19:20:53 所属栏目:Java 来源:网络整理
导读:我在我的代码库中的一个类中有一个方法,对于我的生活,我无法进行我的junit测试. 基本上,当我请求数据库连接时调用此类,如果返回过时连接,则建立新连接 这是我班上的方法片段(为此目的而修剪) public class TCSOracleDataSourceWrapper extends OracleDataSou

我在我的代码库中的一个类中有一个方法,对于我的生活,我无法进行我的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,但如果使用这些工具进行判断,我找不到进入此方法的方法

非常感谢所有帮助

谢谢
达米安

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

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;
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读