我正在创建一个独立的单元测试(使用Spring自动连接一些依赖项)来测试第三方JAR中函数的功能。
要测试的功能是“updateRule”,它更新数据库中的实体。从代码我可以看到该函数使用“@Transactional”注释。 (不能在这里分享第三方JAR)
但是,在运行测试时,updateRule函数失败 “没有活动交易,合并无效”
我相信我已正确配置Spring安装程序以在函数的实现中激活@Transactional注释,如下所示:
1)Spring配置[编辑使用Spring的LocalSessionFactoryBean]:
@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测试
@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:
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();
}
}
我的配置:
Spring:spring-test-3.1.1.RELEASE
注意:自动调整工作正常,因为我在调试测试时已确认。