blo*_*low 36 java junit spring hibernate transactions
我测试我的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是此测试将失败,因为事务已回滚,但插入正常!如果我删除@TransactionConfiguration(defaultRollback=true)了测试通过但是新记录将被插入到数据库中.
@Test
@Transactional
@Rollback(true)
public void testInsert(){
long id = myService.addPerson( "JUNIT" );
assertNotNull(id);
if( id < 1 ){
fail();
}
}
Run Code Online (Sandbox Code Playgroud)
现在可以正确测试传递,但忽略回滚并将记录插入数据库.显然,我addPerson()在myService中注释了方法@Transactional.为什么忽略回滚?
axt*_*avt 30
您需要将事务边界扩展到测试方法的边界.您可以通过将测试方法(或整个测试类)注释为@Transactional:
@Test
@Transactional
public void testInsert(){
long id=myService.addPerson("JUNIT");
assertNotNull(id);
if(id<1){
fail();
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用此方法确保在回滚之前正确写入数据:
@Autowired SessionFactory sf;
@Test
@Transactional
public void testInsert(){
myService.addPerson("JUNIT");
sf.getCurrentSession().flush();
sf.getCurrentSession().doWork( ... check database state ... );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55834 次 |
| 最近记录: |