zeontestpilot
zeontestpilot

Reputation: 31

JUnit, how to test truncating a table

Question for my fellow programmers. I need to test that a SQL statement will truncate a table without actually truncating the table. I do know that I need to disable the constraints before truncating it, but I'm at a lost of how to actually truncate the table without actually causing "permanent damage" to the table.

Sorry if it's already been asked, and thanks in advance!

Edit: I forgot to mention, I'm using Maven, MyBatis, Oracle DB, and Spring (Aspect, Batch). Also, the code works, but within the context of a JUnit, the method needs to be tested. Though how I will assert it is yet another problem I will soon need to deal with.

Upvotes: 3

Views: 1580

Answers (2)

Jordan Davidson
Jordan Davidson

Reputation: 419

While I agree with Alexey that in memory databases are nice I would also suggest that you test you code on a real database. However there isn't (as far as I'm aware) a way to test to see if it really worked without actually truncating the table.

Advice for testing databases.

  1. Make sure your schema is in a versioned file that you can simply upload to an instance and have a working production environment for your service/app
  2. Make sure you can automate spinning up a blank database instance
  3. Be able to take snapshots of your production environment to use in testing.

If you have done these things you can set up a pretty good suite of tests against your database without going to the production environment.

I have written many automated tests against a real postgresql instance using production schema that work something like this.

  1. Spin up postgresql server.
  2. Upload schema to a database.
  3. Insert Test Data.
  4. Run Some Tests.
  5. Kill the postgresql server.
  6. Clean up the files.

UPDATE:

To spin up the database you would

  1. Create a folder to contain the database files using initdb http://www.postgresql.org/docs/9.3/static/app-initdb.html

  2. start the postgres process and point it at those files http://www.postgresql.org/docs/8.2/static/server-start.html

You might have to tweak the security settings in postgresql.conf and pg_hba.conf (this should be automated as well);

Upvotes: 2

Alexey Malev
Alexey Malev

Reputation: 6533

Consider using inmemory database engine for unit tests, such as Derby. This should allow you to truncate table without damaging real data. A good approach is to use different drivers for production and test purposes. This approach is especially convenient if you are using some ORM framework like Hibernate.

Upvotes: 4

Related Questions