I have a C# application which communicates with DB. I want to test some functions which depend on DB. So I want to be sure that DB has an initial state before each test run. I use NUnit to test my application. What means are available to restore an initial state of DB?
Thank you for your help!

- 6,457
- 13
- 70
- 95
-
3Unit test usually mean testing your code in isolation... how about mocking the DB? – Amittai Shapira Nov 18 '10 at 07:12
-
Sometimes I need to test a stored procedure, so there's no way to mock it. Sometimes a test needs a lot of data (not arbitrary, but complex connected) in db. So it's much easier to prepare the data once in db and use it all the time, than mock repositories. – StuffHappens Nov 18 '10 at 07:17
-
2NUnit is for Unit tests, you seem to mix unit and integration tests. – weismat Nov 18 '10 at 07:20
-
Millions of duplicates of this question: http://stackoverflow.com/search?q=unit%20test%20database – cbp Nov 18 '10 at 07:24
5 Answers
You don't unit test interaction with the database. This type of testing is called integration testing. You can use your usual testing tools (NUnit, MSTest, etc) for this, but best is to separate integration tests in a separate project, use a dedicated test database, and run those tests within a transaction (for instance, use TransactionScope) that you rollback. This ensures the data doesn't change and behavior of your tests is predictable, which is very important.
If you can, try to design your application in such a way that it is easy to fake all external sources such as your database to allow you to run (usually faster) unit tests. This however isn't easy. Especially when dealing with an existing application that hasn't been designed for testability. In that scenario I've found integration testing a good way to start.
You may use in memory SQLite database for creating test db environment.
SQLite Nunit & Fluent Nhibernate - Test your data access layer

- 1,919
- 18
- 33

- 331
- 2
- 6
As others have said, you must NOT depend on a DB and it's structure in unit-testing. Hence I would create an Interface which hides the DB from the component which uses it (aka DB abstraction layer) and then implement an in-memory-DB for the sake of unit-testing.
Tables of this in-memory-DB can be implemented using a simple C# HashTable for each DB table.
This seperation also has the benefit of creating a separation in your code between the DB which may change (e.g. move from MySQL to Oracle, etc) from the components which use it.

- 3,488
- 1
- 29
- 46
You should use mockup programs ( plugins) like:
Rhino mocks or moq
those programs can simulate data source like database during testing.

- 2,597
- 4
- 30
- 43
Consider switching to MbUnit for your integration tests. It has very handy Rollback attribute exactly for your needs.
MbUnit has the same attributes for marking test classes and methods as NUnit has. So you'll only need to change the using directives and reference the MbUnit dll's.

- 914
- 1
- 9
- 21