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

前端 未结 4 403
有刺的猬
有刺的猬 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 03:58

    check out

    http://static.springsource.org/spring/docs/2.5.x/reference/testing.html

    Section 8.3.4 in particular

    Spring has some classes for testing that will wrap each test in a transaction, so the DB is not changed. You can change that functionality if you want too.

    Edit -- based on your more infos, you might want to look at

    AbstractTransactionalJUnit38SpringContextTests at

    http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/test/context/junit38/AbstractTransactionalJUnit38SpringContextTests.html

    0 讨论(0)
  • 2020-12-01 04:03

    If your

    myService.addPerson("JUNIT"); 
    

    method is annotated like @Transactional you will be getting some different kind or errors trying to fix this. So you better just test DAO methods.

    0 讨论(0)
  • 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 ... ); 
    } 
    
    0 讨论(0)
  • 2020-12-01 04:10

    Use Following annotation before class :

    @TransactionConfiguration(transactionManager = "txManager",defaultRollback = true)
    @Transactional
    

    here txManager is application context's Transaction Manager.

    Here txManager is an instance or bean id of Transaction manager from application context.

    <!-- Transaction Manager -->
        <bean id="txManager"
              class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean>
    
        <tx:annotation-driven transaction-manager="txManager" />
    

    Add your code inside setUp() method, this will execute in start of the test and the last wrap up code should be put in teatDown() method that will executed at last. or you can also use @Before and @After annotation instead of it.

    0 讨论(0)
提交回复
热议问题