【发布时间】:2011-05-09 04:40:21
【问题描述】:
我测试我的 DAO 和服务没有问题,但是当我测试 INSERTs 或 UPDATEs 时,我想回滚事务而不影响我的数据库。
我在我的服务中使用@Transactional 来管理交易。我想知道,是否有可能知道事务是否会正常,但回滚以防止更改数据库?
这是我的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring.cfg.xml")
@TransactionConfiguration(defaultRollback=true)
public class MyServiceTest extends AbstractJUnit38SpringContextTests {
@Autowired
private MyService myService;
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Test
public void testInsert(){
long id = myService.addPerson( "JUNIT" );
assertNotNull( id );
if( id < 1 ){
fail();
}
}
}
问题是这个测试会失败,因为事务被回滚了,但是插入是可以的!
如果我删除@TransactionConfiguration(defaultRollback=true),则测试通过,但会在数据库中插入一条新记录。
@Test
@Transactional
@Rollback(true)
public void testInsert(){
long id = myService.addPerson( "JUNIT" );
assertNotNull(id);
if( id < 1 ){
fail();
}
}
现在可以正确测试通过,但忽略回滚并将记录插入数据库。
很明显,我在 myService 中用 @Transactional 注释了方法 addPerson()。
为什么回滚会被忽略?
【问题讨论】:
标签: java hibernate spring transactions junit