微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java – 代码覆盖率

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

原文地址:https://www.jb51.cc/java/438163.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐