Search code examples
javaunit-testingintegration-testinghsqldb

In HSQLDB, why is it necessary to drop schema in the "After" method i.e., after the test is completed?


Hey I am writing some unit tests and integration tests using HSQLDB as the database. In the tests, it is recommended to drop the schema's after each unit or integration test. Wont the tables get deleted on their own once test is completed? Or is this done to prevent errors during build time?


Solution

  • It depends on the scope of your HSQLDB instance. If you create one per test and then discard it after the test completes then dropping the schema is redundant but the likelihood is that many devs are not explicitly aware of (or even want to care about) the lifecycle of the HSQLDB instance being used by their test cases hence the recommendation to drop the schema after test completion.

    The goal is test independence; if you drop the schema (or use TRUNCATE SCHEMA <schema_name> AND COMMIT;) after each test then you can be confident that data inserted or mutated by TestA will not trip up TestB etc.

    Of course, test independence could also be achieved by:

    • Ensuring that each test runs in a transaction which is rolled back on completion
    • Ensuring that each test uses a dedicated HSQLDB instance which is stopped on test-completion

    So, there are alternatives and hence any instruction "to drop schema in the “After” method i.e., after the test is completed" must be a recommendation, one which you are free to ignore as long as you are certain that you have somehow addressed the needs of test-independence.