简体   繁体   中英

Reading tomcat server.xml in junit test case

I am using java 7, and tomcat 7. I am writing few tests for my application in jUnit which uses tomcat/conf/server.xml for jndi. Here is the maven suggest folder structure.

src
|___test
    |___java
    |       |___Testcase.java
    |___resources
            |___conf
                   |___server.xml

My sample server.xml would look like this,

<Resource name="jdbc/junit_db"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/junit_db?zeroDateTimeBehavior=round&amp;autoReconnect=true&amp;dumpQueriesOnException=true"
        username="root"
        password="password"
        maxIdle="0"
        minIdle="0"
        initialSize="1"
        maxWait="5000"
        maxActive="50"
        loginTimeout="1000"
        minEvictableIdleTimeMillis="2000"
        timeBetweenEvictionRunsMillis="5000"
        validationQuery="SELECT 1"
        testOnBorrow="true"
        testOnReturn="true"
        testWhileIdle="false"
        logAbandoned="true"
        removeAbandoned="true"
        poolPreparedStatements="true"
        maxOpenPreparedStatements="10000"
        accessToUnderlyingConnectionAllowed="false"
        defaultAutoCommit="false"
        defaultReadOnly="false"
        defaultTransactionIsolation="4"/>

<Resource name="jdbc/junit_hive_db" 
            type="javax.sql.DataSource" 
            factory="com.office.hive.HiveDataSourceFactory" 
            driverClassName="org.apache.hive.jdbc.HiveDriver" 
            url="jdbc:hive2://localhost:10000/default?zeroDateTimeBehavior=round" 
            username="" 
            password="" />

I want to load this server.xml into the IntialContext before running jUnit test cases. How to achieve this?

Followed this link, it has solution for loading jndi into initialcontext manually.

http://www.alexecollins.com/tomcat-context-junit-rule/

Give TomcatJNDI a try. When fed with Tomcat's configuration files it will deliver all JNDI based objects that are declared in these files as soon as they are looked up. The code to achieve this is for example

TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processServerXml(serverXmlFile)
tomcatJNDI.processContextXml(contextXmlFile);
tomcatJNDI.start();

Then you can lookup the objects as you are used to:

DataSource ds = (DataSource) InitialContext.doLookup("java:comp/env/path/to/datasource")

More about TomcatJNDI can be found here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM