Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

junit 4 TransactionalTestExecutionListener insert test data only once for all tests in class?

I have a junit 4 test class testing a DAO.

unit test:

  @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {
      "classpath:/WEB-INF/applicationContext-db.xml",
      "classpath:/WEB-INF/applicationContext-hibernate.xml",
      "classpath:/WEB-INF/applicationContext.xml" })
    @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class})
    @DataSetLocation("test/java/com/yada/yada/dao/dbunit-general.xml")
    @TransactionConfiguration(transactionManager="transactionManager", defaultRollback = true)
    @Transactional
    public class RealmDAOJU4Test {

     @Autowired
     private DbUnitInitializer dbUnitInitializer;

     @Autowired
     private RealmDAO realmDAO;

     @BeforeTransaction
     public void setupDatabase() {
       // use dbUnitInitializer to insert test data
     }

     @Test
     public void testGetById() {
      Integer id = 2204;
      Realm realm = realmDAO.get(id);
      assertEquals(realm.getName().compareToIgnoreCase(
        "South Technical Realm"), 0);
      assertEquals(8, realm.getRealmRelationships().size());
     }

     // more test methods annotated here
}

The @BeforeTransacation method runs before EVERY test method. What I would like to do is: use my DbUnitInitializer to load data into my database - ONCE when the class is created. Then have each test in the class do what it needs to do with the database, then roll back (not commit) it's changes. It seems over kill to re-insert all the same data from my test files before EVERY test. Is there a way to accomplish this?

or

Is the correct way to write these tests to completely load the database before EVERY test? If so, what function does the defaultRollback=true have in this situation?

thanks for helping me along in my thinking...

like image 565
tia Avatar asked Nov 06 '22 08:11

tia


1 Answers

You need to use a TestExecutionListener and set up your database in the beforeTestClass method. See the Annotations section of the Testing chapter in the Spring user guide.

like image 77
Paul Avatar answered Nov 09 '22 04:11

Paul