Monday, 26 July 2010

Spring -Junit - Testing

Create unit tests the Spring way.

This requires version 4.4 of junit (for v2.5.6 of Spring)
Add the SpringTest module to the test libs

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/MyTestConfig.xml")
public class MyClassTest extends AbstractTransactionalJUnit4SpringContextTests // For Tx enabled tests

Can annotate methods with @NotTransactional to not have a TX created for a method in the test. Methods called inside will still
create TX if they require one.

Don't forget to create your own EntityManager of SessionManager for your persistance.


<context:annotation-config />
<context:component-scan base-package="com.stuff"/>
<aop:aspectj-autoproxy/>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>


<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:persistence-test.xml"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="SQL_SERVER" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://127.0.0.1:1433;databaseName=My-TEST" />
<property name="username" value="UserName" />
<property name="password" value="Password" />
</bean>

No comments:

Post a Comment