【问题标题】:How to provide a test datasource in spring?spring如何提供测试数据源?
【发布时间】:2014-02-14 08:37:07
【问题描述】:

我现在正在用 Hibernate 学习 Spring。我有一个 POJO 模型类,用 Hibernate 注释进行注释,称为 Person、PersonDao 接口,它是休眠实现和 PersonService 类。我正在使用注释,因此它们没有在我的 spring-config.xml 中定义为 bean。现在我想为我的 PersonService 类编写一些 JUnit4 测试,但我想在测试时使用不同的数据库。这是我的 spring-config.xml

<context:component-scan base-package="org.example" />
<tx:annotation-driven />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/example" />
    <property name="username" value="root" />
    <property name="password" value="pwd" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            ...
        </list>
    </property>
</bean>

我希望在我的测试中使用 jdbc:mysql://localhost/example_test 数据库。我该如何实现?

【问题讨论】:

  • 你的单元测试不应该使用数据库,因为他们不应该测试数据库,而是你的类,而是尝试类似 mockito code.google.com/p/mockito

标签: java spring hibernate junit


【解决方案1】:
  • jdbc:mysql://localhost/example 移动到配置文件 (db.properties)

    database.uri=jdbc:mysql://localhost/example

  • 将此文件放在类路径中的某个位置(即src/main/resources

  • 在 Spring 上下文中设置属性占位符并使用数据库 URI 属性键

    <context:property-placeholder location="classpath:db.properties" />
    ...
    <property name="url" value="${database.uri}" />
    
  • 在测试类路径(src/test/resources)中创建同名配置文件

  • 将数据库 URI 属性更改为测试值 (jdbc:mysql://localhost/example_test)

    database.uri=jdbc:mysql://localhost/example_test

利润

【讨论】:

    【解决方案2】:

    dataSource 的定义提取到单独的XML 文件中,并在为测试和生产创建应用程序上下文时提供该文件的不同版本(即,spring-config.xmldatasource-prod.xml 用于生产,spring-config.xmldatasource-test.xml 用于测试)。

    或者,您可以使用profiles 区分测试和生产环境,同时为两者使用相同的配置文件集。

    另一种方法是保留dataSource 的通用定义,但将其属性外部化到属性文件中。但它不允许您对不同的环境使用完全不同的定义(例如,生产中的连接池和用于测试的简单DriverManagerDataSource)。

    【讨论】:

      【解决方案3】:

      您可以这样做并使用另一个数据源、会话工厂等指定另一个 spring-context...

      @ContextConfiguration(locations = {
          "/spring-context-test.xml",
      })
      public class MyTestClass extends AbstractTransactionalJUnit4SpringContextTests
      {
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-09-09
        • 2015-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        • 2011-08-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多