Youness HARDI
Youness HARDI

Reputation: 522

Spring Junit Database rollback at the end of test class

I have a lot of existing Spring JUnit tests. All this tests extends an abstract test class. public class ServiceTest extends AbstractServiceTest { But in this abstract class we reinitialize the database. So it will reinitialize the database on each test class

@Before
@Override
public void initGlobal() throws Exception {
    initDatabase();
    ... }

I am asking how I can do a rollback on a test class in the end of execution of its tests ? So i can initialize a database one time and rollback changes in every test class

Upvotes: 1

Views: 823

Answers (1)

karim mohsen
karim mohsen

Reputation: 2254

I think having two profiles is a better option one for testing and other one for development and on the testing profile use memory based database like H2 (here is a good example) and on your development profile use your main database

When running the tests use the testing profile.Instead of doing rolling back or deleting data each time you run your test

If you want to use a real database in unit tests that I totally discourage it.You can use the spring test runner to annotate your class and rollback transactions

@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback=true)
public class YourTestClass {

    @Test
    @Transactional
    public void myTestMethod() {
        // db will get rolled back at the end of the test
    }
}

Upvotes: 1

Related Questions