I am creating a standalone Unit test (which uses Spring to AutoWire a few dependencies) to test the functionality of a function in a 3rd party JAR.
The function that is to be tested is "updateRule" which updates an entity in the DB. From the code i can see that this function uses "@Transactional" annotation. (Cant share the 3rd party JAR here)
However, on running the test the updateRule function fails with "merge is not valid without active transaction"
I believe i have correctly configured my Spring Setup to activate the @Transactional annotation in the function's implementation as follows :
1)Spring Configuration[Edited to use LocalSessionFactoryBean of Spring] :
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackageClasses = {RulesServiceImpl.class, RulesDaoImpl.class})
public class SpringConfig {
@Bean(name="transactionManager")
public HibernateTransactionManager createHibernateTxnMgr(){
HibernateTransactionManager txnMgr = new HibernateTransactionManager();
txnMgr.setSessionFactory(sessionFactoryBean().getObject());
return txnMgr;
}
@Bean
public AbstractSessionFactoryBean sessionFactoryBean(){
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
return sessionFactoryBean;
}
}
2)Junit Test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class TestAppContextCration {
@Autowired
private IRulesService rulesService;
@Test
public void test() {
Rule rule = new Rule();
rulesService.updateRule(rule);
}
}
3)hibernate util thats used :
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
My Configuration :
Spring : spring-test-3.1.1.RELEASE
Note : The AutoWiring is working fine as i confirmed on debugging the test.