Testing code that depends on a database

I often get asked questions about how to test code that relies heavily on a database. People often assume that because an application relies on a database that the test must also rely on a database. Then they get snagged up in all the problems with testing against databases such as not messing up the data for other people and being able to setup the data so that the test can expect a certain result when the Company table is queried for companid 1357, or even which company should be queried for?

“I need a Company record that has more than 500 employees and is publicly traded to test this bit of logic I wrote. Which companyid should I use? Is the data going to change? Should I just create a new test company in the database? I hope nobody touches it.”

My short answer is: Don’t include the database when you’re testing your business logic (unless you are testing business logic that’s in the database, but that’s a whole seperate topic that won’t be covered here).

How do you do that?

  1. Seperate the code that accesses the database from your business logic implementation.
  2. Create a well-defined interface for that data access object. Like ICompanyDataAccess.
  3. Test the business logic by plugging a Mock object in to replace the database implementation of the data access object.

For further reading, refer to this excellent blog post on mock testing with NMock:  http://msdn.microsoft.com/msdnmag/issues/04/10/NMock/

Comments, questions, or experiences relating to mock testing or seperating business logic from data access? Please comment below.