2012-07-04 45 views
1

我參考了Spring Roo In Action(來自Manning的書)。在某個地方它說這本書「袋鼠標記測試類爲@Transactional,使單元測試自動回滾任何變化Jpa測試和Spring自動回滾

這裏的描述方法:

@Test 
@Transactional 
    public void addAndFetchCourseViaRepo() { 
    Course c = new Course(); 
    c.setCourseType(CourseTypeEnum.CONTINUING_EDUCATION); 
    c.setName("Stand-up Comedy"); 
    c.setDescription(
     "You'll laugh, you'll cry, it will become a part of you."); 
    c.setMaxiumumCapacity(10); 

    c.persist(); 
    c.flush(); 
    c.clear(); 
    Assert.assertNotNull(c.getId()); 

    Course c2 = Course.findCourse(c.getId()); 
    Assert.assertNotNull(c2); 
    Assert.assertEquals(c.getName(), c2.getName()); 
    Assert.assertEquals(c2.getDescription(), c.getDescription()); 
    Assert.assertEquals(
     c.getMaxiumumCapacity(), c2.getMaxiumumCapacity()); 
    Assert.assertEquals(c.getCourseType(), c2.getCourseType()); 
    } 

不過,我不知道明白爲什麼這個方法的改變將沒有發生的RuntimeException自動回滾...

回答

4

報價從documentation

默認情況下,框架將爲每個測試創建並回滾事務。您只需編寫可以假定交易存在的代碼。另外,如果測試方法在事務中運行時刪除選定表的內容,則事務將默認回滾,並且數據庫將在執行測試之前返回到其狀態。事務支持通過在測試的應用程序上下文中定義的PlatformTransactionManager bean提供給您的測試類。

因此,換句話說,運行測試的SpringJUnit4ClassRunner總是在測試執行後執行事務回滾。

+0

謝謝!換句話說'@RunWith(SpringJUnit4ClassRunner.class)'加'@ Transactional'加'@ Test'會自動回滾? – balteo

+1

是的。 (另一個證明鏈接:http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/test/context/transaction/TransactionalTestExecutionListener.html) –

0

我試圖找到一種方法,讓我當列表的元素之一失敗的建立(即:把我的自定義異常時),在業務規則中的原因做了回滾

例,(如果列表中的一個元素失敗,則該想法不會記錄任何內容)

public class ControlSaveElement { 

public void saveRecords(List<MyRecord> listRecords) { 

    Boolean status = true; 

    foreach(MyRecord element: listRecords) { 
    // Here is business rules 
    if(element.getStatus() == false) { 
     // something 
     status = false; 
    } 
    element.persist(); 
    } 

    if(status == false) { 
    // I need to do roll back from all elements persisted before 
    } 
} 

... 
} 

任何想法?我正在使用Roo 1.2.2 ..

+0

問你自己的問題 – rptmat57