簡體   English   中英

Spring單元測試和InitialContext

[英]Spring unit testing and InitialContext

我想獲得一個運行Tomcat和Spring 4的簡單集成測試,注入一個spring組件,並使用來自Tomcat的現有數據源配置。 我不想兩次配置我的數據源。 包括我的數據源在內的所有內容都在文件WebContent/WEB-INF/application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
                http://www.springframework.org/schema/data/jpa      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/jee           http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <task:annotation-driven />

    <!-- annotations in bean classes -->
    <!-- context:annotation-config / -->

    <!-- mvc:annotation-driven / -->
    <context:component-scan base-package="com.mycompany.package.**" />

    <jpa:repositories base-package="com.mycompany.package.**" />


    <!-- <aop:aspectj-autoproxy proxy-target-class="true"/> -->

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="jpaDialect" ref="jpaDialect" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="packagePU" />
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
        </property>
        <property name="jpaPropertyMap">
            <props>
                <prop key="eclipselink.weaving">false</prop>
            </props>
        </property>
    </bean>

    <bean id="jpaVendorAdapter"
        class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
        <property name="generateDdl" value="false" />
        <property name="showSql" value="true" />
    </bean>

    <bean id="jpaDialect"
        class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
    <!-- <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 
        <property name="validationMessageSource" ref="messageSource"/> </bean> -->

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames" value="i18n/messages" />
    </bean>

    <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/DefaultDB" />

</beans>

我正在使用本教程http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-ctx-management ,但是我不完全了解我可以在提供數據源的Tomcat上下文中運行我的測試。

目前,我到此為止:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "file:WebContent/WEB-INF/application-context.xml"})
public class SimulatorTest {

    @Autowired
    private ShiftSimulator simulator;

    @BeforeClass
    public void setup() {
        // ??? 

    }


    @Test
    public void testShiftStart() {
        System.out.println("Hello world");
    }

}

目前,在運行測試時出現此錯誤

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:WebContent/WEB-INF/application-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
...
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
...

我完全理解需要有一個InitialContext,但是如何使用Tomcat提供的上下文(包括數據源配置)提供測試? 我不想兩次設置數據源連接憑據。

解決了。 只是為了解決這個問題:Spring嘗試創建dataSource bean,但無法查找JNDI名稱-因為沒有可用的JNDI。

因此,為了進行測試,我剛剛創建了另一個XML文件,該文件覆蓋了bean的dataSource 我忽略了版本控制中的文件,並要求每個開發人員將其復制到位:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="com.sap.db.jdbc.Driver"
        p:url="jdbc:sap://xxx:30015"
        p:username="sa"
        p:password="">
    </bean>

</beans>

在測試類中,我提供了覆蓋dataSource的其他文件引用,因此它絕不會嘗試執行失敗的JNDI查找:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "file:WebContent/WEB-INF/application-context.xml", "file:WebContent/WEB-INF/test-datasource.xml"  })
public class SimulatorTest {
...

TomcatJNDI為這個問題提供了一個舒適的解決方案。 它基於Tomcat的JNDI系統,並且僅在不啟動服務器的情況下初始化Tomcat的JNDI環境。 因此,您可以在測試中或從任何Java SE應用程序中訪問Tomcat配置文件中配置的所有資源。 用法很簡單,例如

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

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

在這里找到更多關於它的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM