我正在尝试在某些出错情况下测试事务回滚机制。我阅读了许多类似的主题,但没有什么能帮助我。以下是我的尝试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/rest-servlet.xml" })
@Transactional
public class TagDaoImplTest extends DatabaseTestCase {
private static final String FLAT_XML_DATASET = "FlatXmlDataSet.xml";
@Autowired
private TagDao tagDao;
@Autowired
private SessionFactory sessionFactory;
@Before
public void setUp() throws Exception {
DatabaseOperation.REFRESH.execute(getConnection(), getDataSet());
}
@Test
public void testAddWithRollback() throws Exception {
addWithRollback("testTagToAdd"); //i suppouse that we tried to add, but somthing went wrong and transaction was rolled back
final Tag testTagToAdd = tagDao.findByTag("testTagToAdd"); // so db must be without changes and i check this
assertNull(testTagToAdd);
}
@Rollback(true) //i want this method to rollback after its work to imitate corrupted transaction
private void addWithRollback(String tag) throws Exception {
tagDao.add(new Tag(tag));
}
}
我的数据访问对象(DAO)长这样:
@Repository("tagDao")
public class TagDaoImpl implements TagDao {
@Override
public void add(Tag tag) {
final Session session = sessionFactory.getCurrentSession();
session.persist(tag);
}
}
但我的测试失败了,因为它在数据库中找到了那个标签(这意味着事务没有回滚)。我尝试了许多不同的方法,比如获取当前会话和事务,并手动调用回滚,但是没有任何效果。你能帮我吗?