Matt Gaidica
Matt Gaidica

Reputation: 554

Unit Testing Destructive Methods

When doing unit tests on models, and database-altering methods/functions, what is the best methodology or mindset for unit testing? For instance, a "publish" function in a model has no test-able behaviors except for pass/fail, and in the case of passing, it modifies the database. Best practice or approach?

Current thoughts would be to create a mirror of the current database before testing, and just change the database selection in my unit test file. Thank you for your suggestions.

Upvotes: 3

Views: 396

Answers (3)

k3b
k3b

Reputation: 14775

If you want to do unit test (=test in isolation):

  • the business logic would execute against a fake database (Repository mock)
  • the test checks if business logic has really called repository-delete method.

If you want an integration test with the business logic and the database you can

  • open a database transaction
  • add data to database via sql
  • execute the business logic that destroys the data just added
  • verify that data is not in database any more (via sql)
  • rollback the database transaction.

Update:

If you are using .NET you should have a look at ndbunit for java dbunit

Upvotes: 6

Morten
Morten

Reputation: 3854

Don't mirror the database... stub it. If you are testing against a database, You are not unittesting.

Upvotes: 1

Adam Dymitruk
Adam Dymitruk

Reputation: 129782

Use xtunit if you are on .net. This will wrap your test in a transaction and roll it back when it's done.

Upvotes: 1

Related Questions