在DAO中注入实体管理器以进行内存数据库单元/集成测试?



我有一个小型的Spring web应用程序,具有典型的MVC服务DAO JPA/Hibernate持久层架构。在生产中,我使用类似JTA的持久化单元。容器通过@PersistenceContext向DAO注入EntityManager的实例。一切都很好。

现在,我想使用内存中的数据库(在本地pc上的容器之外)来测试我的DAO实现。我可以手动创建一个基于RESOURCE_LOCAL的EntityManager。但是,我怎样才能将它自动注入到我的DAO实现中呢?

我看到了这个问题,它表明这是可能的春天。但是怎么做呢?

当然,对于单元测试,我可以使用new MyDAOImpl()并自己注入EntityManager,但稍后,我将想测试注入了DAO实现的服务。我想避免自己把所有东西都接线。。。这可能吗?

在我们的项目中,我们定义了一个不同的单元testing-config.xml,它定义了数据源bean来指向内存中的数据库,如下所示:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="org.hsqldb.jdbc.JDBCDriver" />
        <property name="jdbcUrl"
                value="jdbc:hsqldb:file:/data/data.db" />
        <property name="user" value="sa" />
        <property name="password" value="" />
        <property name="initialPoolSize" value="1" />
        <property name="minPoolSize" value="1" />
        <property name="maxPoolSize" value="50" />
        <property name="maxIdleTime" value="240" />
        <property name="checkoutTimeout" value="60000" />
        <property name="acquireRetryAttempts" value="0" />
        <property name="acquireRetryDelay" value="1000" />
        <property name="numHelperThreads" value="1" />
</bean>

正常的entityManagerFactory定义如下所示,将使用上面的datasource bean:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceUnitName" value="myDoctorPersistenceUnit" />
    <property name="loadTimeWeaver">
        <bean
            class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    </property>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="generateDdl" value="true" />
            <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
        </bean>
    </property>
    <property name="jpaDialect" ref="jpaDialect" />
</bean>

我们使用以下注释运行TestSuite

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={ "/spring-configuration/test-spring.xml" })

希望这能有所帮助!

最新更新