jiluo
jiluo

Reputation: 2346

How to test database access code

I have a db layer. And I want to test db CRUD results I want every single test to be independent, so I just create tables in setUp(), and drop all tables in tearDown(). So is there any good way to test db access independently? I mean I don't need to drop all tables in every test

Upvotes: 0

Views: 302

Answers (2)

Mark Bramnik
Mark Bramnik

Reputation: 42471

there are a couple of approaches.

  1. You can delete all the data after the each test by using "DELETE" statement. As far as I know, deletes are slow) so its less preferable approach.

  2. You can truncate the tables after each test, so that they will be empty.

  3. (My Favorite one) Open a transaction before each test, and rollback it after the test finishes (even successfully!). This way you'll preserve the state in db as it was before the test.

Hope this helps

Upvotes: 1

k3b
k3b

Reputation: 14755

You can do the database tests within a database transaction that will be rolled back after the test.

For example in java / spring you can use the TestContext framework that will create and roll back a transaction for each test.

Upvotes: 1

Related Questions