Is Creating and Dropping Databases During Unit Tests OK?

databaseentity-frameworksql serverunit testing

I am working with EntityFramework 6 code first approach and SQL Server 2014 Express. However, the DBMS may change in future.

That setup allows easily to create a database and add some dummy data for unit tests. Currently, I am creating one database per unit test and drop it after the unit test finished.

I am not sure if creating / dropping a database is such a lightweight operation as creating / deleting a file… So are there any disadvantages with that approach?

Best Answer

The first thing to note is that, if you are creating and dropping DBs as part of your tests, then they aren't unit tests; they're better described as integration tests.

Pedantic point aside, then the key question is, does each test create a different DB, thus can the tests be run in parallel? Or could two tests running at the same time interfere with each other (eg by one dropping the DB half-way through the other's test)?

If they can't run in parallel, then you aren't getting a good return on the time investment of having each test do its own setup and teardown. If you moved this to the test suit setup and teardown functionality, then you'd suffer no new conflict issues between tests and you'd speed up the individual tests.

If they can be run in parallel, then it comes down to a choice. Having each test create and destroy its own DB is cleaner, but it's slower. So take your pick between the two.