Luka
Luka

Reputation: 21

Is it possible to rollback the database after each JUnit test case without using Spring framework?

I'm trying to test the service which updates multiple tables from the database and I want to rollback the database to previous state after each test case. All solutions I have found are using @Transactional and @Rollback from Spring framework, but since my application is not a Spring web application, I would like to use javax @Transactional, which does not work for me.

Is this possible with javax at all or anything else except the Spring?

Upvotes: 0

Views: 1009

Answers (2)

Renato
Renato

Reputation: 2167

Rollback a transaction isn't a good idea for test (integration test) as the constraint may not be validated before the commit.

You should:

  1. have a DB only for integration tests (or an embedded db or a container db or in RAM db)
  2. execute, for example in a class rule or in a test rule, script SQL in order to bring the db in a known status
  3. execute a test
  4. if test modifies the db then run a truncate of tables modified (again or in your class or test rule) and, before peform a new test, run again the script at point 2
  5. run integration tests not so often as unit tests

Upvotes: 1

Alex Chernyshev
Alex Chernyshev

Reputation: 1745

Better idea is to use in-memory database: H2 https://www.h2database.com/ Recommendation for a Java in memory database

Not always and not everything in database can be rolled-back to initial state ( ex. sequences ).

Upvotes: 0

Related Questions