Reputation: 5880
I'm watching this video post (by Jon Galloway and Jesse Liberty) about Building a repository for testing, and they mentioned it's not a good idea to have the DB, and rather one should use a fake repository. The two reasons they gave for that are:
1. The DB may not be available, and
2. Unit tests should be focused at the code level.
So about the first, I never encountered a scenario where I wanted to work on anything and test env. DB wasn't available, and the second point they made I didn't get.
So is it a bad practice using your DB in unit tests? What is the potential harm?
Thanks.
Upvotes: 3
Views: 81
Reputation: 300549
Unit tests should test one thing and have no external dependencies (i.e. test in isolation).
As soon as the file system or a database, or anything external is involved, it is really an integration test.
If a unit test relies on an external dependency, it requires a known state and therefore becomes prone to breaking (fragile).
As @Darin mentions, you can include a Database in an integration test by ensuring a known state by restoring a known database state, running a test in a transaction and rolling back the transaction at the end of the test.
Upvotes: 3
Reputation: 1038780
So is it a bad practice using your DB in unit tests?
It is bad to use database in unit tests but not in integration tests. The idea of unit tests is to test the different layers of your application in isolation. Tying them to a database makes them no longer unit tests as they depend on a database, so they contradict one of the most fundamental rules of a unit test.
So when the time comes to test your actual data access layer (the one that's hitting the database) you should use integration tests. In those tests you should setup a test database. Ideally this database should be in a known state for each integration test. To achieve this you could have scripts that create the database in the test fixture setup and execute the entire integration test into a single atomic transaction that will be rolled back in the test fixture tear down so that the database is again in a known state for the next integration test.
Another approach (if you are using an ORM) is to setup your data access layer in the integration test to use an in-memory database (such as SQLite) which will be created and thorn down for each test.
Upvotes: 5