1

I am in reference to Spring Roo In Action (book from Manning). Somewhere in the book it says "Roo marks the test class as @Transactional so that the unit tests automatically roll back any change.

Here is the illustrating method:

@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());
  }

However, I don't understand why changes in this method would be automatically rolled back if no RuntimeException occurs...

4

2 回答 2

4

Quote from documentation:

By default, the framework will create and roll back a transaction for each test. You simply write code that can assume the existence of a transaction. [...] In addition, if test methods delete the contents of selected tables while running within a transaction, the transaction will roll back by default, and the database will return to its state prior to execution of the test. Transactional support is provided to your test class via a PlatformTransactionManager bean defined in the test's application context.

So, in other words, SpringJUnit4ClassRunner who runs your tests always do transaction rollback after test execution.

于 2012-07-04T12:57:30.320 回答
0

I'm trying to find a method that allows me to do a rollback when one of the elements of a list fails for a reason within the business rules established (ie: when throw my customize exception)

Example, (the idea is not recording anything if one element in list fails)

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
  }
 }

...
}

Any idea? I'm working with Roo 1.2.2..

于 2012-11-21T16:13:05.210 回答