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

I have a junit 4 test class testing 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 is executed before EVERY test method. I would like to do this: use my DbUnitInitializer to load data into my database - ONCE when the class is created. Then each test in the class does what it needs to do with the database, then rollback (not commit), which it changes. It seems like for killing to re-insert all the same data from my test files before each testing. Is there any way to do this?

or

Is the right way to write these tests to fully load the database before EVERY test? If so, which function has a default value of Rollback = true in this situation?

Thank you for helping me in my thoughts ...

+4
source share
1 answer

You need to use TestExecutionListener and configure your database in the beforeTestClass method. See the Annotations Section of the Testing Chapter in the Spring User Guide.

+2
source

All Articles