How to rollback a database transaction when testing services with Spring in JUnit?

前端 未结 4 422
有刺的猬
有刺的猬 2020-12-01 03:19

I have no problem testing my DAO and services, but when I test INSERTs or UPDATEs I want to rollback the transaction and not effect my database.

4条回答
  •  眼角桃花
    2020-12-01 04:09

    You need to extend transaction boundaries to the boundaries of your test method. You can do it by annotating your test method (or the whole test class) as @Transactional:

    @Test 
    @Transactional
    public void testInsert(){ 
        long id=myService.addPerson("JUNIT"); 
        assertNotNull(id); 
        if(id<1){ 
            fail(); 
        } 
    } 
    

    You can also use this approach to ensure that data was correctly written before rollback:

    @Autowired SessionFactory sf;
    
    @Test 
    @Transactional
    public void testInsert(){ 
        myService.addPerson("JUNIT"); 
        sf.getCurrentSession().flush();
        sf.getCurrentSession().doWork( ... check database state ... ); 
    } 
    

提交回复
热议问题