在我們的項目中,我們定義了一個不同的單元測試-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 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" })
希望這有助於!
創建指向內存數據庫的實體管理器不是問題。問題是確保在運行容器外部的junit測試的同時將此實體管理器注入到帶註釋的類中。如何在你的JUnit測試中實現這一點?你有代碼示例嗎?謝謝。 – JVerstry
「你的容器之外」是什麼意思? – Vikdor
當我從NetBeans運行我的JUnit測試時,代碼不會在Tomcat中執行(例如)。因此,我不能使用像持久性單元這樣的JTA連接我的DAO,Service等。我相信我需要使用RESOURCE_LOCAL持久性單元進行junit測試並手動創建實體管理器。 – JVerstry