【问题标题】:Spring unit testing and InitialContextSpring 单元测试和 InitialContext
【发布时间】:2016-01-14 21:53:58
【问题描述】:

我想在运行 Tomcat 和 Spring 4 的情况下进行简单的集成测试,注入一个 spring 组件并使用我现有的来自 Tomcat 的数据源配置。我不想配置我的 DataSource 两次。 包括我的数据源在内的所有内容都在文件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 提供的上下文提供我的测试,包括我的数据源配置?我不想设置我的数据源连接凭据两次。

【问题讨论】:

  • 您可以粘贴您正在使用的 application-context.xml 吗?如果它很大,只需粘贴相关部分。根据我的理解,您可以在 xml 中包含所有内容,而无需两次指定数据源。你不需要做任何初始化。我有工作代码,我从来没有这个问题
  • @user3659052 内容已添加,谢谢
  • 您没有参考您的数据源。做两件事。第一个更改: 和第二个:添加 或您需要定义数据源的任何内容。那么这个错误就会消失
  • 如您所见,@user3659052 两者都已经存在(除了您提到的预期类型,但给出了相同的错误)。对于第二个更改,请查看 entityManagerFactory,其中我引用了我在同一文件中定义的数据源。我没有使用 DAO。该网络应用程序运行良好,除了测试。由于缺少初始上下文,它看起来更像是实际上无法创建 bean“dataSource”。

标签: java spring unit-testing spring-mvc tomcat


【解决方案1】:

解决了。简单回顾一下这个问题:Spring 尝试创建 dataSource bean,但在查找 JNDI 名称时失败——因为没有可用的 JNDI。

所以我为测试做了什么,我只是创建了另一个覆盖 bean dataSource 的 XML 文件。我忽略了版本控制中的文件,并要求每个开发人员复制该文件:

<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 {
...

【讨论】:

  • 假设您使用的是 maven,只需将其放入 src/test/resources 您不应该手动复制文件。
  • 但我不想在我的源代码存储库中拥有我的凭据。
  • 然后将凭据放入每个用户在其文件系统(主目录)上的属性文件中。此外,如果是为了测试为什么拥有它们如此危险,那么您应该为此拥有一个测试帐户,而不是您自己的帐户或生产帐户。让开发人员复制一些内容以进行测试,否则容易出错,最终会咬你。
【解决方案2】:

TomcatJNDI 为这个问题提供了一个舒适的解决方案。它基于Tomcat的JNDI系统,只初始化Tomcat的JNDI环境,不启动服务器。因此,您可以在测试中或从任何 Java SE 应用程序中访问 Tomcat 配置文件中配置的所有资源。用法很简单,例如。 g.

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

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

Find more about it here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2012-12-22
    相关资源
    最近更新 更多