Spring Junit4 Test
捣鼓了差不多一天。。。终于把"No Session found for current thread"问题解决了
环境:Spring 4.0.6 RELEASE + Hibernate 4.2.2 Final
折腾记录如下:
1. 出现"No Session found for current thread",查找配置文件中的sessionFactory配置,确认无误;
2. 检查写的测试用例,并尝试修改注解:@Transactional和@TransactionConfiguration,没解决;
3. 再检查DAO层代码和对应的entity,确认没问题;
4. 搜索"No Session found for current thread",有人说是配置文件中需要加上<prop key="hibernate.current_session_context_class">thread</prop>
试了,结果没有了"No Session found for current thread",但是出现了"HibernateException: contains is not valid without active transaction",表明没有事务,错误更大了。
5. 接着搜索,找到如下blogs:
http://www.iteye.com/topic/1126047
根据以上博客内容,加上Service层代码,并测试通过,郁闷了。。。
http://blog.csdn.net/funi16/article/details/8691575
在看到这个博客后,噢了一声,果断把extends AbstractJUnit4SpringContextTests换成extends AbstractTransactionalJUnit4SpringContextTests,这才把事务管理加进来了,也可以回滚了!
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext_persistence.xml") @TransactionConfiguration(transactionManager = "transactionManager",defaultRollback = true) public class ActionDAOImplTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private ActionService actionServiceImpl; @Autowired private ActionDAO actionDAOImpl; @Test //@Rollback public void testAdd() throws Exception { Action action = new Action(); action.setLoginDate(new Date()); Thread.sleep(2000); action.setLogoffDate(new Date()); action.setUserName("chris"); action.setOperation("add;update;select"); actionServiceImpl.recordAction(action); Action lookUpOne = actionServiceImpl.checkAction(4); Assert.assertEquals("right","add;update;select",lookUpOne.getOperation()); } @Test @Rollback(value = false) public void testAdd2() throws Exception { Action action = new Action(); action.setLoginDate(new Date()); Thread.sleep(2000); action.setLogoffDate(new Date()); action.setUserName("chris"); action.setOperation("add;update;select"); actionDAOImpl.save(action); Action lookUpOne = actionDAOImpl.find(8); Assert.assertEquals("right","add;update;select",lookUpOne.getOperation()); } }