如何在春季提供测试数据源?

Vad*_*nko 5 java junit spring hibernate

我现在正在用Hibernate学习Spring.我有一个POJO模型类,注释了Hibernate注释,称为Person,PersonDao接口,它是hibernate实现和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>
Run Code Online (Sandbox Code Playgroud)

我想在我的测试中使用jdbc:mysql:// localhost/example_test数据库.我如何实现这一目标?

hoa*_*oaz 4

  • 移至jdbc:mysql://localhost/example配置文件 ( db.properties)

    数据库.uri=jdbc:mysql://localhost/example

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

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

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

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

    数据库.uri=jdbc:mysql://localhost/example_test

利润