如何从Context中检索JUNIT测试中的org.jboss.resource.adapter.jdbc.WrappedConnection

时间:2013-10-25 12:50:47

标签: java jdbc junit jboss jndi

我正在尝试在Junit测试类中获取WrappedConnection以测试一些DAO功能。

我有这样的方法

public static List<Top5TermFact> getTop5TrendsForPeriodAndAnalysisRule(long arId, String date,  long analysis_type_id ,WrappedConnection  connection)

所以我的测试类的方法 setUpClass()试图以这种方式获取与数据源的连接:

这里是导入的类:

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.jboss.resource.adapter.jdbc.WrappedConnection;
import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource;

这里是方法代码:

@BeforeClass
public static void setUpClass() throws Exception {
    // rcarver - setup the jndi context and the datasource
    try {

    // Create initial context
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jboss.naming");
    InitialContext ic = new InitialContext();
    ic.createSubcontext("java:/comp");
    ic.createSubcontext("java:/comp/env");
    ic.createSubcontext("java:/comp/env/jdbc");

    // Construct DataSource
    MysqlXADataSource pool = new MysqlXADataSource();
    pool.setURL("jdbc:mysql://192.168.xx.xxx:3306/db_name");
    pool.setUser("root");
    pool.setPassword("password");
    ic.bind("java:/comp/env/jdbc/social_coop", pool);

    Context initContext = new InitialContext();
    Context webContext = (Context) initContext.lookup("java:/comp/env");

    DataSource ds = (DataSource) webContext.lookup("jdbc/social_coop");

    con = (WrappedConnection)ds.getConnection();
    con.setAutoCommit(true);


    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

这会返回异常:

$java.lang.ClassCastException: com.mysql.jdbc.JDBC4Connection cannot be cast
to org.jboss.resource.adapter.jdbc.WrappedConnection at
it.netseven.socialproxy.test.TrendAnalysisRelationsFiller.
setUpClass(TrendAnalysisRelationsFiller.java:92)
[...]

所以问题出在这一行:

con = (WrappedConnection)ds.getConnection();

任何想法? TNX

0 个答案:

没有答案